The subtle difference between for-of and for-in looping structures in JavaScript

The subtle difference between for-of and for-in looping structures in JavaScript

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.

  • 1- for
  • 2- while
  • 3- do while

Other four are

  • 4- map
  • 5- forEach
  • 6- for of
  • 7-for in


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

  • Declare an array?

let arr = [4,5,6]        

  • Now we have changed our mind and we want to treat our arr like an object. i.e key value pairs.
  • Lets push a key Value pair

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.

要查看或添加评论,请登录

Muhammad Afzal的更多文章

社区洞察

其他会员也浏览了