HomeTutorsContact
JavaScript
How to print all the properties of the object in JavaScript?
Gulshan Saini
June 17, 2020
1 min

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

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

Output

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.

Using for-in loop

We can also use for-in loop as follows

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

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

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.

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?

Subscribe to our newsletter!

We'll send you the best of our blog just once a month. We promise.

Related Posts

How to Get Current Date in Human Readable Form in JavaScript?
October 03, 2020
1 min
© 2020, All Rights Reserved.

Quick Links

Advertise with usContact Us

Social Media