Different ways to iterate over object in JavaScript

Let's iterate over an object,

const author = {
  firstName: 'Param',
  lastName: 'Harrison',
  age: 31
};

Using in operator on object

in operator can be used to iterate over all the keys of the object.

// Iterating using `in` operator
for (const key in author) {
  console.log(`${key}: ${author[key]}`);
}

Using of operator and Object.entries method

In the last blog post, we have used the of operator on Object.entries to iterate over an object. You can check out the post here

// Iterating using `of` and `entries` method
for (const [key, value] of Object.entries(author)) {
  console.log(`${key}: ${value}`);
}

Similar to the entries method, you can also convert all the keys into an array and iterate over the array.

// Getting all the keys in the array
for (const key of Object.keys(author)) {
  console.log(`${key}: ${author[key]}`);
}

There will be several other ways to iterate over an object, share your preferred way in the comments.

Check out the code example here,