HomeTutorsContact

How to print all the properties of the object in JavaScript?

By Gulshan Saini
Published in JavaScript
June 17, 2020
1 min read

Say you have following person object and you want to print all the properties on console.

const person = {
  name: 'Madame Uppercut',
  age: 39,
  secretIdentity: 'Jane Wilson',
  powers: ['Million tonne punch', 'Damage resistance', 'Superhuman reflexes']
}

Since, this is very basic example, the output is going to be same for all of methods shown below

Output

name
age
secretIdentity
powers

Let’s explore various methods to print all the properties of the object in JavaScript.

Using Object.keys()

First way to print all properties of person object is by using Object.keys() method. In this method we pass the person object to Object.keys() as an argument. This method returns array which can be further iterated using the forEach() method as shown below.

Object.keys(person).forEach(prop => console.log(prop))

Using for-in loop

We can also use for-in loop as follows

for (let prop in person) {
  console.log(prop)
}

for...in loop enumerates properties in the prototype chain as well. Make sure to use hasOwnProperty() method to print only properties of object itself.

for (let prop in person) {
  if (person.hasOwnProperty(prop)) {
    console.log(prop)
  }
}

Tip: for...in should not be used to iterate over an Array where the index order is important.

Using for…of loop

ECMAScript 6 added support of for...of which works as follows

for (const prop of Object.keys(person)) {
  console.log(prop)
}

Using Object.entries()

ECMAScript 8 added support of Object.entries() and it returns an array of a given object’s own properties with its values. In this method we pass the person object to Object.entries() as an argument. This method returns array which can be further iterated using the forEach() method as shown below.

Object.entries(person).forEach(
  ([prop]) => console.log(prop);
)

We have used array destructuring here to iterate through objects.

Tip: for...of , Object.keys() and Object.entries() iterate only object's own properties and excludes properties from prototype chain. If you have complex object avoid using the for...in loop.

Of all the methods described above I find Object.entries() clean and short to iterate over object properties. Make sure to use a pollyfill to support old browsers.


Tags

#javascript
Previous Article
How to check the SEO score of the webpage using the Chrome browser?

Related Posts

JavaScript
JavaScript get tomorrow's date
December 13, 2021
1 min
Gulshan Saini

Gulshan Saini

Fullstack Developer

Topics

Angular
JavaScript
Linux
ReactJS
Typescript

Subscribe to our newsletter!

We'll send you the best of our blog just once a month. We promise.
© 2022, All Rights Reserved.

Quick Links

Contact UsBrowserCSSPythonPuppeteer

Social Media