Loops can execute a block of code a number of times. They are perfect for situations where you need to run the same code over and over again, each time with a different value.
The for loop has three optional expressions, separated by semicolons:
for (expression 1; expression 2; expression 3) {
// code block to be executed
}
A simple loop that counts from 0 to 4:
for (let i = 0; i < 5; i++) {
console.log("The number is " + i);
}
For loops are most commonly used to iterate over arrays.
const cars = ["BMW", "Volvo", "Saab", "Ford"];
for (let i = 0; i < cars.length; i++) {
console.log(cars[i]);
}
let to declare your counter variable (like
i). This ensures the variable is only available inside the loop's block
scope.
Expressions in a for loop are optional. For example, you can omit the first
expression if your values are already set:
let i = 2;
let len = cars.length;
for (; i < len; i++) {
text += cars[i];
}
for loop is the most versatile looping structurelet) is the best practice for loop
countersi <= cars.length instead of i < cars.length reads one index past the end of the array, giving undefined on the last iteration.
A second example that does real work with the loop instead of just printing values:
const prices = [12.50, 8.75, 20.00, 15.25];
let total = 0;
for (let i = 0; i < prices.length; i++) {
total += prices[i];
}
let average = total / prices.length;
console.log("Total: " + total + ", Average: " + average.toFixed(2));
Q: What's the difference between for and while loops?
A: for is best when you know how many times to loop (like array length). while is better when the number of iterations depends on a condition that isn't a simple counter.
Q: Can I loop backwards?
A: Yes — start at the last index and decrement: for (let i = arr.length - 1; i >= 0; i--).
Q: What happens if I write an infinite loop by mistake?
A: The browser tab freezes or eventually shows a "page unresponsive" warning. See the MDN for loop reference for the exact evaluation order that causes this.