JavaScript Array.keys() Method

Shubham Vora Jan 30, 2023
  1. Syntax of JavaScript Array.keys():
  2. Example Code: Use the Array.keys() Method With the Array of Numbers
  3. Example Code: Compare the Output of the Object.keys() and array.keys() Methods
JavaScript Array.keys() Method

In JavaScript, the array.keys() method is used to get the keys of every index of the reference array. The method creates the new iterable object and embeds all the keys of the current array.

Syntax of JavaScript Array.keys():

let arr = ["Hello", "Delft", 30];
let iterableObject = arr.keys();

Parameters

This method doesn’t take any parameter values.

Return

The Array.keys() method returns the new iterable object of all keys of the arr.

Example Code: Use the Array.keys() Method With the Array of Numbers

In the example below, we created the array of numbers. We have used the array.keys() method to get the iterable object of keys of all indexes of the array.

You can see in the output that iterable is an object and array iterator. Also, we are iterating through the iterable object using the for loop and printing the iterable object’s values.

let arr = [20,40,50];
let iterable = arr.keys();
console.log(iterable);
for(let x of iterable){
    console.log(x);
}

Output:

Object [Array Iterator] {}
0
1
2

Example Code: Compare the Output of the Object.keys() and array.keys() Methods

We have created the array of strings in this example. The array also contains some empty elements.

When we find the keys of the array indexes using the Object.keys(arr) method, it ignores the empty values, but the arr.keys() method doesn’t.

The example below shows that the array contains the empty value at the third index. So, the returned object from the Object.keys(arr) method doesn’t have the 2 key value as it ignores the empty value.

let refarr = ["Delft","stack", ,"Hello"];
let arrrayIterable = [...refarr.keys()];
console.log(arrrayIterable);
let Objectiterable = Object.keys(refarr);
console.log(Objectiterable);

Output:

[ 0, 1, 2, 3 ]
[ '0', '1', '3' ]
Author: Shubham Vora
Shubham Vora avatar Shubham Vora avatar

Shubham is a software developer interested in learning and writing about various technologies. He loves to help people by sharing vast knowledge about modern technologies via different platforms such as the DelftStack.com website.

LinkedIn GitHub

Related Article - JavaScript Array