JavaScript For Loop
Loops execute a block of code a number of times. The for loop is used when you know in advance how many iterations you need.
The for Loop
Syntax: for (init; condition; increment). (1) init runs once before the loop starts, (2) condition is checked before each iteration, (3) increment runs after each iteration.
Basic for Loop
for (let i = 0; i < 5; i++) {
console.log("Iteration:", i);
}Looping Through an Array
Array Iteration
const fruits = ["Apple", "Banana", "Cherry", "Mango"];
for (let i = 0; i < fruits.length; i++) {
console.log(i + ": " + fruits[i]);
}The for...in Loop
The for...in loop iterates over the keys (property names) of an object.
for...in — Object Keys
const person = { name: "Alice", age: 30, city: "Paris" };
for (let key in person) {
console.log(key + ": " + person[key]);
}The for...of Loop
The for...of loop iterates over the values of an iterable (array, string, Set, Map, etc.).
for...of — Array Values
const colors = ["red", "green", "blue"];
for (let color of colors) {
console.log(color);
}
// Also works on strings:
for (let char of "Hello") {
console.log(char);
}| Loop | Iterates Over | Best For |
|---|---|---|
| for | index (0, 1, 2...) | Known number of iterations |
| for...in | Object property keys | Enumerating object properties |
| for...of | Iterable values | Arrays, strings, Sets, Maps |
| forEach() | Array element + index | Array callbacks (no break) |
Nested Loops
Multiplication Table (3x3)
for (let i = 1; i <= 3; i++) {
let row = "";
for (let j = 1; j <= 3; j++) {
row += (i * j) + "\t";
}
console.log(row);
}📝 Note: Use for...of (not for...in) to loop over arrays. for...in is for objects and can iterate inherited properties.
Exercise:
How many parts does a standard for loop statement have?