Open In App

JavaScript Object keys() Method

Improve
Improve
Like Article
Like
Save
Share
Report

The Object.keys() method in JavaScript is used to retrieve an array of the enumerable property names of an object. It returns an array containing the keys of the object.

Syntax:

Object.keys(obj);

Parameter:

  • obj: It is the object whose enumerable properties are to be returned.

Return Value:

It returns an array of strings that represent all the enumerable properties of the given object.

Object keys() Method Examples

Example 1: Enumerating Array Indices with Object.keys()

The code uses the Object.keys() method to retrieve the enumerable properties of the array [‘x’, ‘y’, ‘z’] and logs them to the console. Since arrays in JavaScript are also objects, their indices are treated as properties. Therefore, the output will be [‘0’, ‘1’, ‘2’].

JavaScript
// Returning enumerable properties
// of a simple array 
let check = ['x', 'y', 'z'];
console.log(Object.keys(check));

Output
[ '0', '1', '2' ]

Example 2: Enumerating Array-Like Object Properties with Object.keys()

Here, an array-like object “check” has three property values { 0: ‘x’, 1: ‘y’, 2: ‘z’ } and the object.keys() method returns the enumerable properties of this array. The ordering of the properties is the same as that given by the object manually.

JavaScript
// Returning enumerable properties
// of an array like object.
let object = { 0: 'x', 1: 'y', 2: 'z' };
console.log(Object.keys(object));

Output
[ '0', '1', '2' ]

Applications

It can be used for returning enumerable properties of a simple array, an array-like object & an array-like object with random key ordering.

Exceptions

  • It causes a TypeError if the argument passed is not an object.
  • If an object is not passed as an argument to the method, then it persuades it and treats it as an object.

We have a complete list of JavaScript Object methods, to check those please go through this JavaScript Object Complete Reference article.

Supported Browser:


Last Updated : 14 Mar, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads