JavaScript for Loop Explained

JavaScript provides a for loop, similar to Java or C#, to repeatedly execute code based on a condition.

Syntax

    for (initializer; condition; iteration) {
        // Code to execute
}

for loop consists of three main parts:

  • Initializer: Sets up a counter variable.
  • Condition: Defines a condition to control the loop.
  • Iteration: Increments or decrements the counter.

Example: Basic for Loop

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

Output:

0 1 2 3 4

Example: Loop Through an Object's Properties

Instead of looping through an array, we can iterate over an object's properties using a for...in loop.

        const user = {
        name: "John",
        age: 25,
        city: "New York"
    };

    for (let key in user) {
        console.log(`${key}: ${user[key]}`);
    }

Output:

name: John
age: 25
city: New York 

Points to Remember

  • JavaScript for loops execute code repeatedly.
  •  Consists of initializer, condition, and iteration.
  •  Curly brackets { } wrap the code block.
  •  Initialization can be done before the loop.
  •  JavaScript supports for...in and for...of loops.