for

A loop with a counter: initialization, condition, and step. Repeats a block of code while the condition is true.

On this page

Example

#
JavaScript
for (let i = 1; i <= 3; i++) {
  console.log(`Lesson ${i}`)
}
Console
Lesson 1
Lesson 2
Lesson 3

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

#
Syntax
for (initialization; condition; afterthought) {
  // statements
}

More examples

#
Walking an array with an index
JavaScript
const ranking = ['Mia', 'Emma', 'Jack']

for (let i = 0; i < ranking.length; i++) {
  console.log(`${i + 1}. ${ranking[i]}`)
}
Console
1. Mia
2. Emma
3. Jack
Counting down in steps of 3
JavaScript
const countdown = []

for (let i = 10; i > 0; i -= 3) {
  countdown.push(i)
}

console.log(countdown)
Console
[10, 7, 4, 1]
Nested loops
JavaScript
for (let row = 1; row <= 3; row++) {
  let line = ''
  for (let col = 1; col <= 3; col++) {
    line += row * col + ' '
  }
  console.log(line.trim())
}
Console
1 2 3
2 4 6
3 6 9

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 to length - 1, so the last turn would read undefined. 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 use filter().
  • If you don’t need the index, pick for...of. The code is shorter and you can’t be off by one.

Related entries

#

Spotted a mistake or missing an example? Write to us.