For Loop
Classic for Loop
Print numbers from 0 to 4. The loop uses i as a counter variable,
starting at 0. The condition i < 5 ensures the loop continues to execute as long as the
counter is less than 5, resulting in exactly 5 iterations (from 0 to 4).
for (let i = 0; i < 5; i++) {
console.log(i);
}
Key Points:
- Three parts of a for loop: initialization (
let i = 0), condition (i < 5), and update (i++) - Loop runs while condition is true: the loop stops when the condition becomes false
- Counter variable tracks iterations: i starts at 0 and increases by 1
each time.
i++meansi = i + 1
Classic for Loop: Iterating Through an Array
This example shows how to use the loop index i to access array elements and perform operations within the loop body.
const names = ["Alice", "Bob", "Charlie", "David"];
for (let i = 0; i < names.length; i++) {
const name = names[i];
const greetings = `Hello, ${name}`;
console.log(greetings);
}
Key Points:
- Use
i < array.lengthfor the condition: the loop runs exactly once for every element in the array - Access elements with index:
names[i]gets the element at position i - Index matches array position: the first element is at index 0, second at index 1, and so on
Classic for Loop: Starting from any Index
The loop variable i just matches the array index, and you can start from any valid index.
In this example we want to print last three elements of the array, we use
numbers.length - 3 to calculate the starting index dynamically. This ensures
we always access the last 3 elements, even if you change the array and add more numbers.
const numbers = [10, 1, 5, 20, 30, 7];
for (let i = numbers.length - 3; i < numbers.length; i++) {
console.log(numbers[i]);
}
Key Points:
- Start anywhere in the array: change the initialization to begin at any valid index
- Calculate index dynamically: using
array.length - 3adapts automatically if the array size changes - Access only the elements you need: useful for processing a part of an array
Classic for Loop: Iterating Backwards Through an Array
for loop can iterate in reverse order - from last to first element. Start from the last
index (array.length - 1),
use i >= 0 as the condition (loop to the first index) , and decrement with
i--.
This example iterates backwards through an array of 3 strings.
const items = ["first", "second", "third"];
for (let i = items.length - 1; i >= 0; i--) {
const item = items[i];
console.log(item);
}
Key Points:
- Start from the last index: use
array.length - 1to begin at the end of the array - Decrement instead of increment: use
i--to count backwards.i--meansi = i - 1 - Condition checks for >= 0: the loop continues until it reaches and processes the first element - element with index 0
The for..of Loop: arrays
The for..of loop lets you iterate over arrays. It gives you direct
access to each element, always from first to last. It doesn't give you the index of the element.
const results = [
{ name: "Alice", score: 85 },
{ name: "Bob", score: 70 },
{ name: "Charlie", score: 92 }
];
const passed = [];
for (const result of results) {
if (result.score > 80) {
const studentName = result.name;
passed.push(studentName);
}
}
Key Points:
- Simpler syntax than classic for: no index variable or manual incrementing needed
- Direct access to elements: each iteration gives you the actual array element, not its index
- Cannot access the index: use a classic for loop if you need to know element positions
- All elements are processed: the loop runs exactly once for every element in the array - from first to last
The for..of Loop: strings
The for..of loop can also iterate over strings, giving you access to each character
one at a time - always from first to last character. This example checks whether each character in
"hello" is a vowel or consonant.
const word = "hello";
for (const char of word) {
if ('aeiouAEIOU'.includes(char)) {
console.log(`${char} is a vowel`);
} else {
console.log(`${char} is a consonant`);
}
}
Key Points:
- Strings are iterable:
for..ofworks on strings just like it does on arrays - Each character is processed: you get one character per iteration
- Order is preserved: always iterates from the first character to the last