Difference between for-in and for-of in JavaScript
Hello Everyone,
Today I would like to share something about new looping techniques in JavaScript. We may know and used some of the loops available in JavaScript like for, while and do while.
The ES6 standards brought us two new kind of loops : for-in and for-of. We are familiar with the for loop, but what is this new one with extra “in” and “of”? Lets learn about this…
For-in loop
Basically, for-in loop lets us to loop through the properties of an object. Didn’t understand? For instance, lets take an object like below
let air = {
nitrogen : 78,
oxygen: 21,
other:1
};
If we want to log the properties of this object with their values to the console, we can say like
for(let key in air) {
console.log(key, air[key]);
}
The result would be like this :
nitrogen 78
oxygen 21
other 1
The variable “key” I have used in the code points to each property of the object in the loop.
For-of loop
As for-in loop helps us to loop through the properties of an object, for-of loop helps to loop through the items of an array. Before seeing an example, I would like to show you that using for-in loop also, we can loop through an array. Interesting, isn’t it? Just like objects are key-value pairs, arrays are also key-value pairs but the difference is that in array, indexes are the keys. First, lets loop through an array using for-in loop
let colors = [ "red", "orange", "yellow", "green", "blue", "indigo" , "violet" ];for(let key in colors) {
console.log(key, colors[key]);
}//result
0 red
1 orange
2 yellow
3 green
4 blue
5 indigo
6 violet
Before the advent of for-of loop, we would have used for loop to loop through the array like below
for(let i=0; i<colors.length; i++) {
console.log(colors[i]);
}//result
red
orange
yellow
green
blue
indigo
violet
As in the code above, we have to initialize an iterator, give a condition and add an incrementor in the for loop. Pheww… Too much work for a simple thing. Now, I will show you how to get the same result using for-of loop.
for(let color of colors) {
console.log(color);
}//result
red
orange
yellow
green
blue
indigo
violet
Isn’t Simple! Hope you start using for-in and for-of loop in your code.
Summary :
For-in loop : used to loop through the properties of an object
For-of loop : used to loop through the items of an array
Happy Coding! :)