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’.


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 ( 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 ( loop:

The 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) {

The output will be

// output:
2 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 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) {

The output is:


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


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