The Object.getOwnPropertyNames() method returns an array of all the properties found in a given object.
Example
getOwnPropertyNames() Syntax
The syntax of the getOwnPropertyNames() method is:
Object.getOwnPropertyNames(obj)
Here, getOwnPropertyNames() is a static method. Hence, we need to access the method using the class name, Object.
getOwnPropertyNames() Parameters
The getOwnPropertyNames() method takes in:
- obj - the object whose properties are to be returned.
getOwnPropertyNames() Return Value
The getOwnPropertyNames() method returns an array of strings corresponding to the properties in the given object.
Example 1: JavaScript Object.getOwnPropertyNames()
In the above example, we have used the getOwnPropertyNames() with the obj object which returns an array including all property names or keys.
The result is stored in the objProperties object, which shows the specified array when logged to the console.
Example 2: getOwnPropertyNames() With Array-like Objects
In the above example, we have created an array-like object obj having random integers as the keys.
The getOwnPropertyNames() method, when used with obj, returns an array of numeric strings in ascending order.
Example 3: getOwnPropertyNames() With Arrays
In the above example, we have used an array named arr with the getOwnPropertyNames() to find the properties present in the array.
The output consists of indexes of the array along with the length property. The length property is the built-in property of the array in JavaScript that returns the number of elements in the array.
Example 4: getOwnPropertyNames() With Non-Enumerable Properties
In the above example, we first created an object obj with some initial properties.
We then added the girlFriend property using the defineProperty() method and configured the enumerable to false.
As we can see from the output, the Object.getOwnPropertyNames() method returns both the enumerable and non-enumerable properties of obj.
On the other hand, the Object.keys() method only returns the enumerable properties.
Remember: Object.getOwnPropertyNames() returns all the enumerable and non-enumerable properties of the object while Object.keys() returns all the enumerable properties of the object.
Recommended Reading: