JavaScript for..of loop

Thisfor...ofLooping is my favorite way of looping in JavaScript.

It combines simplicityforEachHave the ability to break the cycle.

The syntax is like this:

const list = ['a', 'b', 'c']

for (const item of list) { console.log(item) }

You can use interrupt at any timebreak:

const list = ['a', 'b', 'c']

for (const item of list) { console.log(item) if (item === ‘b’) break }

You can use skip iterationcontinue:

const list = ['a', 'b', 'c']

for (const item of list) { if (item === ‘b’) continue console.log(item) }

You can get the iterative index usingentries():

const list = ['a', 'b', 'c']

for (const [index, value] of list.entries()) { console.log(index) //index console.log(value) //value }

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

Download mine for freeJavaScript beginner's manual


More js tutorials: