JavaScript(JS) object method - getOwnPropertyNames

w‮itfigi.ww‬dea.com

In JavaScript, the Object.getOwnPropertyNames() method is used to get an array of all the property names of an object. These property names include both enumerable and non-enumerable properties.

The syntax for using Object.getOwnPropertyNames() is as follows:

Object.getOwnPropertyNames(obj)

Where obj is the object whose property names you want to retrieve.

Here's an example of using Object.getOwnPropertyNames():

const person = {
  name: 'John',
  age: 30,
  city: 'New York'
};

const propertyNames = Object.getOwnPropertyNames(person);

console.log(propertyNames);
/* Output:
["name", "age", "city"]
*/

In this example, we create an object called person with three properties: name, age, and city. We then call Object.getOwnPropertyNames() on the person object to get an array of all its property names. The resulting propertyNames array contains the names of all three properties.

It's important to note that Object.getOwnPropertyNames() only works with own properties of an object, and not inherited properties. If the object has no own properties, an empty array will be returned. Also, this method only returns the names of string properties, so properties that have symbol keys will be excluded from the resulting array.