What is getOwnPropertyNames in JavaScript?

The getOwnPropertyNames method will return all the direct and non-enumerableproperty that doesn’t show up in for…in loop properties of the object. The symbols are not included.

Syntax

Object.getOwnPropertyNames(obj)

Here, obj is the object whose properties you want to be returned.

This method returns an array of strings of enumerable and non-enumerable properties.

Example

let male = {gender : "male"};
let user = Object.create(male);
user.name = "Ram";
user.age = 22;
user[Symbol('symbol')] = "symbol";
// defining non enumerable prooperty
Object.defineProperty(user, "non_enumerable", {
enumerable : false
});
console.log("The user object is ", user);
let ownProperties = Object.getOwnPropertyNames(user);
console.log("\nPrintting Own Properties of user object\n")
console.log(ownProperties);

In the code above, we have created a user object from the male object. We have added name, age, non_enumerable property, and a symbol to the user object. When we call getOwnPropertyNames with the user object as an argument, we will get all of the direct enumerable (name, age) and non-enumerable (non_enumerable) properties. The symbol and inherited properties are skipped.

Free Resources