JavaScript Loops
JavaScript provides many way to iterate through loops. This tutorial explains all the various loop possibilities in modern JavaScript
Introduction
JavaScript provides many way to iterate through loops. This tutorial 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 usingbreak
- You can fast forward to the next iteration of a
for
loop usingcontinue
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.
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
ES6 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
}
//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
.
for…in vs for…of
The difference with for...in
is:
for...of
iterates over the property valuesfor...in
iterates the property names
→ I wrote 17 books to help you become a better developer:
- C Handbook
- Command Line Handbook
- CSS Handbook
- Express Handbook
- Git Cheat Sheet
- Go Handbook
- HTML Handbook
- JS Handbook
- Laravel Handbook
- Next.js Handbook
- Node.js Handbook
- PHP Handbook
- Python Handbook
- React Handbook
- SQL Handbook
- Svelte Handbook
- Swift Handbook
Also, JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025