The subtle difference between for-of and for-in looping structures in JavaScript
Muhammad Afzal
?? Vue Js ?? React & Next.js Developer | ???? JavaScript Engineer | ??? Frontend Architect | ?? Pixel-Perfect Innovator | ??? UI/UX Specialist
There are a total of seven ways for looping in JAVASCRIPT.
First three are common in almost all of the modern languages. So we wouldn't waste time to explore them in depth.
Other four are
The most confusing are for of and for in.
Let's unveil what's beneath them.
Point to remember
Basically, every data type that we declare in JavaScript has a prototype in the form of an object. i.e Object.prototype
let arr = [4,5,6]
arr.prop = val;
Now how would you like to retrieve it?
In the form of an array or keys of an object's values ?
领英推荐
Every object will inherit the objCustom property and every object that is an Array will inherit the arrCustom property since these properties have been added to Object.prototype and Array.prototype, respectively. The object iterable inherits the properties objCustom and arrCustom because of inheritance and the prototype chain.
Our code so far,?
Object.prototype.objCustom = function() {}
Array.prototype.arrCustom = function() {};
let arr = [4,5,6]
arr.prop = val;
Wanna retrieve it like an array?
for (let element of arr) {
?console.log(element);
??// logs 4, 5, 6
}
Wanna retrieve it like keys of an object ?
for (const key in arr) {
?console.log(key);?
?// logs "0", "1", "2", "prop", "arrCustom", "objCustom"
}
Want to retrieve only those keys which are solely declared in the scope of arr?
for (const key in arr) {
?if (arr.hasOwnProperty(key)) {
??console.log(key);
???// logs "0", "1", "2", "prop"
?}
}
Confused..?
hasOwnProperty(key) is already implemented in browsers. So, for..in will always return those keys which are solely declared in the scope of arr.
Last shot , want to retrieve key value pairs?
let arr = ["hello", "javaScrict"]
for([idx, value] of arr.entries()) {
console.log(idx, '=', value)
}
/*
0 '=' 'hello'
1 '=' 'javaScript'
*/
Hope you enjoyed the article...!
Cheers ..!
follow Muhammad Afzal for more in-depth articles on CSS , JavaScript , React and SEO.