JAVASCRIPT

JavaScript For Loop: Syntax, Usage, and Examples

In JavaScript, a for loop is a control structure that repeats a block of code a certain number of times. For loops are ideal for iterating over arrays, objects, and other repeatable operations.

How to Use the For Loop in JavaScript

The syntax of the for loop in JavaScript uses three expressions: initialization, condition, and incrementation. Here's the basic structure:

for (initialization; condition; incrementation) {
		// Execute the loop body as long as the condition is true
    statement(s);
}
  • for: The statement to create a for loop.
  • initialization: Typically sets a counter variable.
  • condition: The loop continues to execute as long as this condition evaluates to true. As soon as the condition returns false, to loop ends.
  • incrementation: Updates the loop counter at the end of each loop iteration.

When to Use the For Loop in JavaScript

The for loop is ideal for situations where you know the number of iterations before the loop starts. Such scenarios include processing items in an array or repeating an action a specific number of times.

Iterating Over Collections

For loops are great for accessing the elements of collections like arrays and strings. Other iterable objects include objects, maps, and sets.

const fruits = ['apple', 'banana', 'cherry'];
for (let i = 0; i < fruits.length; i++) {
    console.log(fruits[i]);
}

Repeating Actions

A for loop is also useful when you want to repeat an action a certain number of times.

for (let i = 0; i < 3; i++) {
    console.log();
}

Examples of For Loops in JavaScript

Because of their flexibility, for loops are the most common type of loop in JavaScript. Here are a few examples:

Generating a Table of Contents

A common use of for loops in web development is creating a dynamic table of contents based on page headings:

const headings = document.querySelectorAll('h2');
const toc = document.getElementById('tableOfContents');

for (let i = 0; i < headings.length; i++) {
    let li = document.createElement('li');
    li.textContent = headings[i].innerText;
    toc.appendChild(li);
}

Data Processing for Charts

Within an analytics platform, a for loop might help process arrays of data to create a chart:

const data = [5, 10, 15, 20, 25];
const scaledData = [];

for (let i = 0; i < data.length; i++) {
    scaledData.push(data[i] * 10); // Scale data for charting
}
console.log(scaledData); // Outputs: [50, 100, 150, 200, 250]

Animation Frames

In a game, a for loop might iterate through frames or elements to animate them and update their states:

const frames = document.querySelectorAll('.frame');
for (let i = 0; i < frames.length; i++) {
    frames[i].style.animationDelay = `${i * 100}ms`;
}

Learn More About the For Loop in JavaScript

Nested For Loops

Nested for loops are useful for working with multi-dimensional arrays or grids. This example uses a nested for loop to iterate over a 2D array.

const matrix = [
    [1, 2],
    [3, 4]
];
for (let i = 0; i < matrix.length; i++) {
    for (let j = 0; j < matrix[i].length; j++) {
        console.log(matrix[i][j]);
    }
}

For Of Loop in JavaScript

Introduced with ES6, the for of loop simplifies iterating over collections like arrays, strings, maps, sets, and more. Without needing a counter variable, for of loops reduce the risk of index errors, infinite loops, and other bugs.

Here’s the example from above, using a for of loop instead of a for loop:

const fruits = ['apple', 'banana', 'cherry'];
for (const fruit of fruits) {
    console.log(fruit);
}

For Each Loop in JavaScript

JavaScript's array forEach() method is another form of loop that executes a function once per array element. forEach() is an alternative to the traditional for loop and the more modern for of loop.

Again, here’s the example from before, using forEach():

const fruits = ['apple', 'banana', 'cherry'];
fruits.forEach(fruit => console.log(fruit));

For In Loop in JavaScript

The for in loop iterates over the properties of an object. This loop is ideal when you need to iterate over properties or methods of an object.

const person = { firstName: "John", lastName: "Doe" };
for (let key in person) {
    console.log(key, person[key]);
}

For vs. While Loop in JavaScript

For loops and while loops in JavaScript are similar but serve different purposes. In essence, choosing between a for loop and a while loop depends on whether you know the total number of iterations ahead of time.

For loops are well-suited for definite iterations. While loops, on the other hand, are great for indefinite iterations where conditions can change.

let success = false;
let attempts = 0;

while (!success && attempts < 5) {
    success = tryLogin(); // A function that attempts to log in and returns true if successful
    attempts++;
    console.log(`Attempt ${attempts}: ${success ? 'Successful' : 'Failed'}`);
}

Break in JavaScript For Loops

The break statement in JavaScript is a control structure to prematurely exit from a loop. break is particularly useful when you find the result you were looking for and no longer need to continue the loop.

For example, consider searching an array for a specific value. You can use break to exit the loop immediately once you've found the value.

const numbers = [3, 45, 74, 12, 6];
let found = false;

for (let i = 0; i < numbers.length; i++) {
    if (numbers[i] === 12) {
        found = true;
        console.log("Number found at index:", i);
        break;  // Exits the loop once 12 is found
    }
}
if (!found) {
    console.log("Number not found.");
}

Using break can significantly optimize performance, especially in loops that process large datasets or complex algorithms. break terminates the loop as soon as you achieve a desired outcome. In doing so, you reduce the number of iterations, saving computation time and resources.

Learn JavaScript for Free
Start learning now
button icon
To advance beyond this tutorial and learn JavaScript by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

You can code, too.

© 2024 Mimo GmbH