13
110

How to write JavaScript ES6 for-loop

Reading Time: 2 minutes

Iteration one of the most use method to access elements in data structure such as arrays, set and map. There are also various forms of loop such as while-loop, do-while loop and for-loop. What we will be discussing here is specifically to for-loop.

Vanilla for-loop

In the vanilla way, we have always been writing for-loop in this manner.

var array = ['One', 'Two', 'Three']; 

for(var i = 0; i < array.length; i++) {
  console.log(array[i]); 
}

More info at mozilla.

With the introduction of ES6, 2 main methods of writing for-loop have been introduced for different usage.

  • for..of
  • for..in

Iterating with for-of

Accessing user name in an array of user objects.

const users = [
        {name: 'First Person', age: '16'}, 
        {name: 'Second Person', age: '17'}, 
        {name: 'Third Person', age: '18'}, 
]; 

for(const user of users) {
  console.log(user.name); 
}

Output:

First Person
Second Person
Third Person

for..of variation gives you the flexibility of accessing the objects element in a sequential way without the need to specify the index in the array.

Iterating with for-in

Using for..in to access the list of user

const users = [
        {name: 'First Person', age: '16'}, 
        {name: 'Second Person', age: '17'}, 
        {name: 'Third Person', age: '18'}, 
]; 

const specialUser = {
        name: "Special Person",
        age: "99"
};

// Example 1
for(const key of users) {
  console.log(users[key].name); 
}

// Example 2
for(const key of specialUser) {
  console.log(key); 
}

Output:

// Example 1
First Person
Second Person
Third Person

// Example 2
name
age

As you can see that for..in seems to be operating like the normal vanilla style in example 1 but it can be good for use-case such as you do not need to know what keys exist in an object and just want to display them.

Conclusion

To choose which version to write, it depends on your criteria that is most important to you. If performance very important, then vanilla is recommended. But if readability is more preferred, then for..of or for..in style will help to reduce your codes!

Show Comments

No Responses Yet

Leave a Reply