for
A loop with a counter: initialization, condition, and step. Repeats a block of code while the condition is true.
Example
#for (let i = 1; i <= 3; i++) {
console.log(`Lesson ${i}`)
}Definition and usage
#A classic for loop has three parts in its parentheses, separated by semicolons. The first runs once at the start and usually creates a counter. The second is the condition, checked before every turn. The third runs after every turn and usually increments the counter.
It works well when you need an index, want to step through every few elements, go backward, or cover only part of an array. If you’re simply walking every element, for...of or array methods like forEach() and map() read better.
Declare the counter with let. Then every turn gets its own copy of the variable, and the counter doesn’t exist outside the loop. You can skip any of the three parts, but the semicolons must stay: for (;;) is an infinite loop, which you can only stop with break or return.
Syntax
#for (initialization; condition; afterthought) {
// statements
}More examples
#const ranking = ['Mia', 'Emma', 'Jack']
for (let i = 0; i < ranking.length; i++) {
console.log(`${i + 1}. ${ranking[i]}`)
}const countdown = []
for (let i = 10; i > 0; i -= 3) {
countdown.push(i)
}
console.log(countdown)for (let row = 1; row <= 3; row++) {
let line = ''
for (let col = 1; col <= 3; col++) {
line += row * col + ' '
}
console.log(line.trim())
}Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- Watch out for the condition
i <= array.length. Indexes go up tolength - 1, so the last turn would readundefined. Correct:i < array.length. - Don’t remove array elements (e.g. with
splice()) while walking forward through it, since it’s easy to skip the next element. Go from the end instead, or usefilter(). - If you don’t need the index, pick
for...of. The code is shorter and you can’t be off by one.
Related entries
#- for...ofWalks the successive values of an iterable object: an array, a string, a Map, a Set, and others.
- whileRepeats a block of code while the condition is true. The condition is checked before every turn.
- breakImmediately ends a loop or a switch statement and moves on to the code right after it.
- continueSkips the rest of the current loop turn and moves straight to the next one.
- Array.prototype.forEach()Calls a function for every element of the array.
Spotted a mistake or missing an example? Write to us.