The JavaScript Object.getOwnPropertyNames()
method is an integral part of object manipulation and introspection, allowing developers to retrieve an array of all properties (including non-enumerable properties) found directly upon a given object. This function facilitates operations on object properties, especially when you need a reliable way to handle properties regardless of their enumerability.
In this article, you will learn how to effectively use the Object.getOwnPropertyNames()
method in different contexts. Explore how to employ this method to extract property names from objects and understand when and why to use this method over others, such as Object.keys()
or for...in
loops.
Define a simple object with a mix of enumerable and non-enumerable properties.
Use Object.getOwnPropertyNames()
to get all property names.
const person = {
name: 'John',
age: 30
};
Object.defineProperty(person, 'id', {
value: '123456',
enumerable: false
});
const propertyNames = Object.getOwnPropertyNames(person);
console.log(propertyNames);
This code first defines an object person
with properties name
and age
. Then, it adds a non-enumerable property id
using Object.defineProperty
. When Object.getOwnPropertyNames()
is called, it retrieves all the properties including the non-enumerable id
.
Understand that properties inherited from a prototype are not included.
Define an object that inherits properties and examine its own properties.
const proto = {
inheritedProp: 'inherited'
};
const childObject = Object.create(proto);
childObject.ownProp = 'own';
const ownPropertyNames = Object.getOwnPropertyNames(childObject);
console.log(ownPropertyNames);
This code snippet shows how Object.getOwnPropertyNames()
deals with inherited properties. childObject
inherits inheritedProp
from proto
but only lists properties defined directly on it, such as ownProp
.
Object.keys()
Realize that Object.keys()
only lists enumerable properties.
Compare outputs of Object.keys()
and Object.getOwnPropertyNames()
.
const exampleObject = {
visibleProp: 'visible',
invisibleProp: 42
};
Object.defineProperty(exampleObject, 'invisibleProp', {
enumerable: false
});
const keys = Object.keys(exampleObject);
const propNames = Object.getOwnPropertyNames(exampleObject);
console.log('Object.keys():', keys); // ['visibleProp']
console.log('getOwnPropertyNames():', propNames); // ['visibleProp', 'invisibleProp']
In the above example, Object.keys()
does not include the non-enumerable invisibleProp
while Object.getOwnPropertyNames()
does.
The Object.getOwnPropertyNames()
function in JavaScript is crucial for retrieving all property names, including non-enumerable ones, from an object. Whether checking property existence, debugging, or serializing objects without missing properties, this method proves essential. By understanding and using techniques discussed, you manage object properties more effectively, ensuring comprehensive property manipulation and introspection in JavaScript development.