/

The Object getOwnPropertyNames() Method: A Guide

The Object getOwnPropertyNames() Method: A Guide

In JavaScript, the getOwnPropertyNames() method of the Object object is used to retrieve a list of all the names of the own properties of a given object. This method returns an array that includes both enumerable and non-enumerable properties. However, it does not consider inherited properties.

It’s important to note that non-enumerable properties are not iterated upon. In other words, they are not listed in loops like for..of, rendering them inaccessible through regular enumeration methods.

If you are only interested in obtaining a list of the enumerable properties, you can use the Object.keys() method instead. This method specifically retrieves the names of the enumerable properties.

Let’s take a look at an example to better understand how the getOwnPropertyNames() method works:

1
2
3
4
5
const dog = {};
dog.breed = 'Siberian Husky';
dog.name = 'Roger';

Object.getOwnPropertyNames(dog); // [ 'breed', 'name' ]

In the example above, we create a dog object and assign two properties to it: breed with the value of 'Siberian Husky', and name with the value of 'Roger'. By calling Object.getOwnPropertyNames(dog), we retrieve an array containing the names of the own properties of the dog object: ['breed', 'name'].

Tags: JavaScript, Object.getOwnPropertyNames(), Object properties