How to print or enumerate properties of a JavaScript object?

I usually come across the following requirements,

  • How to print name of all the properties of an object?
  • How to print only the methods of an object?
  • How to print even non-enumerable properties of an object?

In this post, we will explore all the options to iterate and print properties of a JavaScript object. Let us consider the object cat, as shown in the listing below:

By default, for all properties of an object enumerable is set to true. So right now, if we print description of cat’s canRun and name properties using the Object.getOwnPropertyDescriptor, we will find enumerable value true for the both properties.

As you notice besides enumerable, configurable and writable are also set to true.

image

Let us start with printing all properties which enumerable is true.

Printing all enumerable properties using for..in loop

We can print all enumerable properties either own or inherited of cat object using JavaScript for..in loop.

Using the for..in loop, all enumerable properties can be iterated. Above for loop will print all the enumerable properties of cat object.

Read full article on the Infragistics blog