ES6 for loops: Best Practices

Sahil Bondre - Aug 24 '19 - - Dev Community

For loops are common control flow statements used to iterate over range, sequential data types etc. The ES6 revision of JavaScript provides several new features making the language more powerful, crisp and elegant. Here's what I came across as the best practices for the for loop:

Vanilla for loop

// Old and Bad way

for(var i = 0; i < 10; i++) {
  // Do Stuff
}
// End of loop

console.log(i)
// 10
// iterator still accessible after the end of the loop
Enter fullscreen mode Exit fullscreen mode

Using var to initialize the iterator in the traditional for loop causes it to be accessible even after the loop is over. A better alternative is to use the newer let keyword to initialize the iterator.

// Better way

for(let i = 0; i < 10; i++) {
  // Do Stuff
}
// End of loop

console.log(i)
// undefined
// iterator not accessible
Enter fullscreen mode Exit fullscreen mode

The let keyword limits the scope of the iterator to the for loop block only.

Newer flavors of for loop

The ES6 revision also provides two new for loops the for..of and for..in loop.

for..of:

let primes = [2, 3, 5, 7];

for(const value of primes) {
  console.log(value);
}
// 2
// 3
// 5
// 7
// Iterates over the values of the array
Enter fullscreen mode Exit fullscreen mode

for..in:

let primes = [2, 3, 5, 7];

for(const key in primes) {
  console.log(key);
}
// '0'
// '1'
// '2'
// '3'
// Iterates over the keys of the array
Enter fullscreen mode Exit fullscreen mode

Notice that the for..in loop here returns the keys in the form of strings and not numbers as one would expect. Another weird thing about the for..in loops is that they can iterate thru an object while the for..of loop cannot:

let sandwich = {
  grilled: true,
  butter: "lots",
  bread: "whole wheat",
  calories: 250
}

for(const value of sandwich) {
  console.log(value)
}
// Error: Objects are not iterable

for(const key in sandwich) {
  console.log(key)
}
// "grilled"
// "butter"
// "bread"
// "calories"
Enter fullscreen mode Exit fullscreen mode

const vs let

If you were reading until now really carefully, you would have noticed that I have use let in the vanilla for loop and const in the ES6 flavors of for loops. The vanilla for just increases the initial iterator value and there is a single scope for the whole loop. Thus using const won't work as increasing the iterator value in the next iteration will result in an error. In the newer loops however, every iteration creates a new scope. Thus we can use const as well as let in these loops. const is more preferred in such cases as we don't want to change the value of the iterable.

And that's it folks! Thankyou for reading and have a great day 😄

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player