JavaScript provides many way to iterate through loops. This lesson explains each one with a small example and the main properties.

for

const list = ['a', 'b', 'c']
for (let i = 0; i < list.length; i++) {
  console.log(list[i]) //value
  console.log(i) //index
}
  • You can interrupt a for loop using break
  • You can fast forward to the next iteration of a for loop using continue

do...while

const list = ['a', 'b', 'c']
let i = 0
do {
  console.log(list[i]) //value
  console.log(i) //index
  i = i + 1
} while (i < list.length)

You can interrupt a while loop using break:

do {
  if (something) break
} while (true)

and you can jump to the next iteration using continue:

do {
  if (something) continue

  //do something else
} while (true)

while

const list = ['a', 'b', 'c']
let i = 0
while (i < list.length) {
  console.log(list[i]) //value
  console.log(i) //index
  i = i + 1
}

You can interrupt a while loop using break:

while (true) {
  if (something) break
}

and you can jump to the next iteration using continue:

while (true) {
  if (something) continue

  //do something else
}

The difference with do...while is that do...while always execute its cycle at least once.

for...in

Iterates all the enumerable properties of an object, giving the property names.

for (let property in object) {
  console.log(property) //property name
  console.log(object[property]) //property value
}

for...of

ES2015 introduced the for...of loop, which combines the conciseness of forEach with the ability to break:

//iterate over the value
for (const value of ['a', 'b', 'c']) {
  console.log(value) //value
}

How can you get the index of an iteration?

The loop does not offer any syntax to do this, but you can combine the destructuring syntax introduced in ES2015 with calling the entries() method on the array:

//get the index as well, using `entries()`
for (const [index, value] of ['a', 'b', 'c'].entries()) {
  console.log(index) //index
  console.log(value) //value
}

Notice the use of const. This loop creates a new scope in every iteration, so we can safely use that instead of let.

The difference with for...in is:

  • for...of iterates over the property values
  • for...in iterates the property names

Array.forEach

Introduced in ES5. Given an array, you can iterate over its properties using list.forEach():

const list = ['a', 'b', 'c']
list.forEach((item, index) => {
  console.log(item) //value
  console.log(index) //index
})

//index is optional
list.forEach(item => console.log(item))

unfortunately you cannot break out of this loop.


Go to the next lesson