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
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
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
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
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"
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 😄
Top comments (9)
About for..in, in the code, you wrote:
for(const key of primes) {
Instead of
for(const key of primes) {
Yup fixed! Thank you for pointing it out.😄
Just wanted to thank you for this awesome explanation.
I am glad that I was helpful to someone 😄.
You made a typo at the code example of 'for .. in'.
Nice summary!
Fixed!
Thank you!.
No word about performance Sahil) what about?
Performance wise the vanilla for loop would be your best bet. Thank-you for pointing this out, I'll focus on the performance aspects as well in my next posts.
Nice describe