JavaScript : Retrieve the keys or indices of array elements

Java Script @

JavaScript arrays offer a plethora of methods for efficient manipulation and traversal. Among these, the keys() method is particularly useful for extracting array keys or indices. In this article, we’ll delve into the functionality of keys(), its syntax, functionality, and practical applications with detailed examples.

Understanding keys()

The keys() method in JavaScript returns a new Array Iterator object that contains the keys for each index in the array. It provides a convenient way to retrieve the keys or indices of array elements, facilitating iteration and manipulation.


The syntax for keys() is straightforward:


Here, array represents the array for which the keys need to be retrieved.


Let’s explore various scenarios to understand the utility of keys():

Example 1: Basic Usage

const fruits = ['apple', 'banana', 'orange', 'grape'];
const keysIterator = fruits.keys();
// Output: 0
// Output: 1
// Output: 2
// Output: 3

Example 2: Iterating Over Keys

const nums = [10, 20, 30, 40];
for (const key of nums.keys()) {
// Output:
// 0
// 1
// 2
// 3

Example 3: Converting Keys to Array

const nums = [10, 20, 30, 40];
const keysArray = Array.from(nums.keys());
// Output: [0, 1, 2, 3]

The keys() method in JavaScript simplifies array key retrieval and iteration, providing a concise and efficient solution. Whether it’s extracting keys for manipulation or iterating over array indices, keys() streamlines the process with its simplicity and effectiveness.

Author: user