Episode 18 of 46
JavaScript For Loops
Learn the for loop — the most common loop in JavaScript.
The for loop is the most commonly used loop in JavaScript. It combines initialization, condition, and increment in one line.
Syntax
for (initialization; condition; increment) {
// code to repeat
}
Basic Examples
// Count from 1 to 5
for (let i = 1; i <= 5; i++) {
console.log(i);
}
// Count from 10 to 0
for (let i = 10; i >= 0; i--) {
console.log(i);
}
// Count by 2s
for (let i = 0; i <= 20; i += 2) {
console.log(i); // 0, 2, 4, 6, ... 20
}
Looping Through Arrays
let fruits = ["apple", "banana", "cherry", "date"];
for (let i = 0; i < fruits.length; i++) {
console.log(`${i + 1}. ${fruits[i]}`);
}
// 1. apple
// 2. banana
// 3. cherry
// 4. date
For...of Loop (Modern)
let colors = ["red", "green", "blue"];
for (let color of colors) {
console.log(color);
}
// No need to manage an index variable!
For...in Loop (Objects)
let person = { name: "Alice", age: 25, city: "London" };
for (let key in person) {
console.log(`${key}: ${person[key]}`);
}
// name: Alice
// age: 25
// city: London
Nested Loops
for (let i = 1; i <= 3; i++) {
for (let j = 1; j <= 3; j++) {
console.log(`i=${i}, j=${j}`);
}
}
// Produces 9 combinations