Open In App
Related Articles

JavaScript Object keys() Method

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
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.

Example 1: In this example, an array “check” has three property values [‘x’, ‘y’, ‘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 a simple array
let check = ['x', 'y', 'z'];
console.log(Object.keys(check));

                    

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

Example 2: In this example, 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' ]

Example 3: In this example, an array-like object “check” has three property values { 70: ‘x’, 21: ‘y’, 35: ‘z’ } in random ordering and the object.keys() method returns the enumerable properties of this array in the ascending order of the value of indices.

Javascript

// Returning enumerable properties of an array
// like object with random key ordering.
let object = { 70: 'x', 21: 'y', 35: 'z' };
console.log(Object.keys(object));

                    

Output
[ '21', '35', '70' ]

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:

  • Google Chrome 5.0
  • Microsoft Edge 12.0
  • Firefox 4.0
  • Opera 12.0
  • Safari 5.0


Last Updated : 18 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads