JavaScript(JS) object method - keys

The keys() method is a built-in method of the JavaScript Object constructor. It returns an array of a given object's own property names, in the same order as we get with a for...in loop, but with the difference that the keys() method returns only the enumerable property names.

Here's the syntax:

ref‮igi:ot re‬ftidea.com
Object.keys(obj)

where obj is the object for which to get the keys. This method takes only one argument, which is the object for which to get the keys.

Here's an example that shows how to use the keys() method:

const myObj = { prop1: "value1", prop2: "value2" };
console.log(Object.keys(myObj)); // ["prop1", "prop2"]

In this example, we create an object myObj with two properties prop1 and prop2. We use the keys() method to get an array of the object's own property names. Since the object has two properties, the keys() method returns an array with two elements: ["prop1", "prop2"].

The keys() method is useful for getting an array of an object's own property names. Note that this method only returns the enumerable property names. To get all the property names, including non-enumerable ones, you can use the getOwnPropertyNames() method.