for(… in …) v/s for(… of ..)

Lizen Shakya
2 min readMay 15, 2022

One of the basic structure of commands used in high-level languages are ‘Loops’.

loop

Often in a JavaScript script, we iterate over some objects of few built-in classes like Arrays, Dictionaries, Strings, Maps, etc. We iterate the objects using loops. JavaScript supports different kinds of loops:

  • for loop
  • for (..in) loop
  • for (..of) loop
  • while loop
  • do-while loop

Node.js ships with the for…of and for…in loops. These two loops provide a convenient iteration besides the common for loop. Both loops gives us a clean syntax for iterations and quick access to keys or values.

Here in this example we will see more in details and difference between these loops.

for (..in..) loop:

The for...in statement iterates over the properties of an object.

The for…in loop iterates through the keys of an iterable. Iterating over arrays returns the item’s index.

const names = [ 'James', 'Marcus', 'Tim' ]

for (const index in names) {
console.log(index)
}

The output will be

// output:
0
1
2

for...in is an extremely useful way to iterate through object properties.

const user = { name: 'Tim', loves: 'Coding' }

for (const key in user) {
console.log(`${key}: ${user[key]}`)
}

// output:
// name: Tim
// loves: Coding

Takeaway: Avoid using for/in over an array unless you're certain you mean to iterate over non-numeric keys and inherited keys.

for (..of..) loop:

The for...in statement is useful for iterating over object properties, but to iterate over iterable objects like arrays and strings, we can use the for...of statement. The for...of statement is a newer feature as of ECMAScript 6.

for...of, you get access to the array element itself. The assigned variable in a for…of loop receives an item’s value.

// Initialize array of items
let items = [ "chocolate", "doll", "hammer" ];

// Print out each type of items
for (let item of items) {
console.log(item);
}

The output is:

"chocolate" 
"doll"
"hammer"

Takeaway: the for…of loop provides an iterable’s values. for...of throws error while iterating through object properties.

Conclusion

Loops are an integral part of programming in JavaScript, and are used for automating repetitive tasks and making code more concise and efficient.

--

--