JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to use for...of loop to iterate over an object in JavaScript?

In JavaScript, objects are not iterable. Therefore, if you try to use for/of loop to iterate over an object, you will get TypeError.

let product = {
  name:'Amazon Echo Dot',
  price:39.99,
  quantity:25
};
for(let pdt of product){ //TypeError
  console.log(pdt);
}

But if you want to use for/of loop to iterate through the properties of an object, then use Object.keys() method. Object.keys() method returns an array of properties of an object, and arrays are iterable with for/of loop.

let product = {
  name:'Amazon Echo Dot',
  price:39.99,
  quantity:25
};
for(let key of Object.keys(product)){
  console.log(key);
}

Output

name
price
quantity

If you want to iterate through the values of properties of an object, then use Object.values() method.

let product = {
  name:'Amazon Echo Dot',
  price:39.99,
  quantity:25
};
for(let value of Object.values(product)){
  console.log(value);
}

Output

"Amazon Echo Dot"
39.99
25

You can also iterate through key-value pairs using Object.entries() method and use array destructuring to extract key and value to distinct variables.

let product = {
  name:'Amazon Echo Dot',
  price:39.99,
  quantity:25
};
for(let [key, value] of Object.entries(product)){
  console.log(`${key}: ${value}`);
}

Output

name: Amazon Echo Dot
price: 39.99
quantity: 25

Recommended Posts