JavaScript loop

JavaScript provides many ways to traverse the loop. This tutorial introduces all the various loop possibilities in modern JavaScript

Introduction

JavaScript provides many ways to traverse the loop. This tutorial illustrates each example with a small example and main attributes.

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 interruptforrecyclebreak
  • You can fast forward to the next iterationforrecyclecontinue

Each

Introduced in ES5. Given an array, you can use the following methods to traverse its propertieslist.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 escape this cycle.

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 interruptwhilerecyclebreak:

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

You can use jump to the next iterationcontinue:

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 interruptwhilerecyclebreak:

while (true) {
  if (something) break
}

You can use jump to the next iterationcontinue:

while (true) {
  if (something) continue

//do something else }

Difference fromdo...whilethat's itdo...whileAlways execute its loop at least once.

for...in

Iterate over all enumerable properties of the object and provide the property name.

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

for...of

ES6introducedfor...ofLoop, combining the simplicity and breaking power of forEach:

//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 }

Pay attention to useconst. The loop creates a new scope in each iteration, so we can safely use it insteadlet.

for...inversusfor...of

Difference fromfor...inYes:

  • for...of Traverse attribute values
  • for...in Iteration property name

Download mine for freeJavaScript beginner's manual


More js tutorials: