offline version v3


6 of 264 menu

for statement

The for construct sets a loop: a code placed inside it will be repeated a given number of times.

Syntax

for (initial commands; loop termination condition; commands after loop iteration) { loop body };

Example

Let's output a sequence of numbers from 0 to 10:

for (let i = 0; i <= 10; i++) { console.log(i); }

Example

Let's output a sequence of numbers from 10 to 0:

for (let i = 10; i >= 0; i--) { console.log(i); }

Example

Let's output even numbers from 0 to 10:

for (let i = 2; i <= 10; i += 2) { console.log(i); }

Example

Let's output array elements:

let arr = ['a', 'b', 'c', 'd', 'e']; for (let i = 0; i < arr.length; i++) { console.log(arr[i]); }

Example

The initial commands and commands after loop iteration may consist of not one, but several commands separated by commas. For example, let's make two counters: let the first one increase by one each loop iteration, and the second one - by two:

for (let i = 0, j = 0; i <= 9; i++, j += 2) { console.log(i, j); }

See also

  • the lesson from JavaScript tutorial
    detailing how to work with the for loop
  • the for-of statement
    that creates a loop to iterate over an array
  • the for-in statement
    that creates a loop to iterate over an object
  • the while statement
    that also creates a loop
  • the break statement
    that breaks a loop
  • the continue statement
    that moves a loop to next iteration
enru