What is Object.keys in JavaScript?

The Object.keys method will return an array that contains the property name of the object – the symbols and non-enumerable properties are not included. The order of the returned properties is the same as the order that occurs in the for...in loop.

Syntax

Object.keys(obj)

Example

let male = {gender : "male"};
let user = Object.create(male);
user.name = "Ram";
user.age = 20;
user.getName = function(){
return this.name;
}
user[Symbol("symbol")] = "symbol";
Object.defineProperty(user, "non-enumerable", {
enumerable: false
})
console.log("The user object is ", user);
console.log("\nKeys of the user object is ", Object.keys(user))
// non-enumerable properties,symbols and inherited properties are not included in the keys

In the above code, we have:

  1. Created the user object from male object.
  2. Added symbol as a property key to user object .
  3. Added a non-enumerable property to user objecct.

When we call the Object.keys method by passing the user object as an argument, we will get an array of its own object properties. It doesn’t include:

  1. Symbol
  2. Inherited propertiesIn our case, male object properties are inherited properties that are not included.
  3. Non-enumerable propertiesProperties that don’t occur in for…in loop

To get an object’s own enumerable and non-enumerable properties, we can use Object.getOwnPropertyNames.

Free Resources