In Javascript, The for loop is a control flow statement that allows us to repeatedly execute a block of code a specified number of times.
for (initialization; condition; iteration) { // Code to be executed in each iteration }
Initialization: Executed once before the loop starts. It is used to declare and initialize the loop variable.
Condition: Checked before each iteration. If the condition is true, the loop continues; otherwise, it terminates.
Iteration: Executed after each iteration. It is typically used to update the loop variable.
for (let i = 1; i <= 10; i++) { console.log(i); }
> 1 > 2 > 3 > 4 > 5 > 6 > 7 > 8 > 9 > 10
Initialization: let i = 1 initialize the loop variable i to 1.
Condition: i <= 10 specifies that the loop will continue as long as i is less than or equal to 10.
Iteration: i++ increments the value of i by 1 after each iteration.
We can also nest for loops to create more complex looping structures.
for (let i = 1; i <= 3; i++) { for (let j = 1; j <= 3; j++) { console.log(i * j); } }
> 1 > 2 > 3 > 2 > 4 > 6 > 3 > 6 > 9
The for...in loop is used to iterate over the enumerable properties of an object. It is often used with objects, not arrays.
let person = { name: "Alice", age: 25, occupation: "HR" }; for (let key in person) { console.log(key + ": " + person[key]); }
The for...of loop is used to iterate over iterable objects such as arrays, strings, and other iterable objects introduced in ECMAScript 6 (ES6).
The for...of loop simplifies iteration over array elements compared to the traditional for loop.
let colors = ["red", "green", "blue"]; for (let color of colors) { console.log(color); }