ES2015 Loops

Colter Ulrich
2 min readMar 1, 2021

Even if you’re new to coding, you’ve probably came across the good ol’ for loop:

for (let i = 0; i < array.length; i++){
console.log(‘oh hai’)
}

While this common control flow statement is totally fine for all intents and purposes (and still probably the most versatile), ES2015 provides some clean looking revisions:

for..of and for..in

for..of iterates over the elements of an array:

const odds = [1,3,5,7,9]for (const element of odds){    
console.log(element)
}
// 1
// 3
// 5
// 7
// 9

for..in iterates over the keys for each index in the array:

const odds = [1,3,5,7,9]for (const index in odds){
console.log(index)
}
// 0
// 1
// 2
// 3
// 4

Notice that we are able to use const when defining a variable inside these new loops. This works because every iteration creates a new scope, which is not the case with the classic for loop we all hold so dearly.

Let’s also see how these loops work with objects instead of arrays.

const dude = {
abides: true,
drink: “White Russian”,
hasRug: false,
donny: “Out of his element”
}

for..of:

for (const value of dude){
console.log(value)
}
// Uncaught TypeError: dude is not iterable

for..in:

for (const key in dude){
console.log(key)
}
// abides
// drink
// hasRug
// donny

So it seems that the for..of loop is not able to iterate over an object, while the for..in loop is. Hmm.

While the classic for loop is definitely more versatile, I think these ES2015 additions to the JavaScript loop family offer a fresh alternative for simple looping tasks.

Happy coding!

--

--