← flaviocopes.com

JavaScript Loops

Published Apr 11 2018

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
}

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:



Wanna go from noobie to expert?

I wrote an entire book on this topic 👇

I also got a super cool course 👇

© 2023 Flavio Copes Flavio Copes using Notion to Site Notion to Site

Interested in solopreneurship?