For..in vs For...of loop JavaScript !!

Out of different ways to loop over arrays in Javascript for is used mostly by everyone as it is simple with starting and ending clearly defined.

basic for loop syntax ---

for ([intialization]; [coditionalExpression]; [incrementExpression]){
 statement
}

For...in loop

for...in statement iterates(loops) over all enumerable including inherited enumerable properties of an object. Iteration is performed in arbitrary order.

enumerable simply means countable. As objects in javascript has multiple properties like proto, hasOwnProperty etc, so we don't want to iterate on these non-enumerable properties as their enumerable flag defaults to false.

Lets create an object user with few properties as name, role, right & email

const user = {
  name : 'hashnode',
  role :'developer',
  right : 'edit',
  email : 'user@email.com'
}

Now, lets iterate the object using for...in

for(const prop in user){
  console.log(prop)
}

//Output
name 
role 
rights 
email

to check if property is enumerable we can use propertyIsEnumerable property of javascript object as below.

obj.propertyIsEnumerable('name')
true

obj.propertyIsEnumerable('__proto__')
false
Why Use for ...in

Mostly for the purpose of checking properties where property acts as the "key" of an object.

Note : for....in should not be used to iterate over array where index order is needed.

For...of loop

for...of statement iterate over iterable objects like String, Array, Map, Set. They are fastest on small data sets. For-in statement iterates and logs values that arrayObj as an iterable object defines to be iterated over.

Here we can see values are logged of arrayObj.

const arrayObj = ['apple','orange','pineapple','grapes']

for (const prop of arrayObj ) {
  console.log(prop);
}

//output
apple 
orange 
pineapple 
grapes

That's all I have on this topic. Do let me know your thoughts and feedback below. Hope you learned something new through this! Feel free to reach out to me on Twitter and LinkedIn

Did you find this article valuable?

Support Anup Gurung by becoming a sponsor. Any amount is appreciated!