JavaScript Array keys() method


The keys() method in JavaScript is used to create a new array iterator object that contains the keys (or indices) of each element in an array. This method is particularly useful when you need to access the indices of the elements without needing their corresponding values.

Syntax:

let arrayIterator = array.keys();

Return Value:

  • A new Array Iterator object that contains the keys (indices) of the array.

Key Points:

  • The keys() method does not modify the original array.
  • The resulting iterator can be traversed using methods like next(), or it can be used in a loop (such as a for...of loop) to iterate over the keys.

Example 1: Basic usage

let array = ['a', 'b', 'c']; let iterator = array.keys(); console.log(iterator.next().value); // 0 console.log(iterator.next().value); // 1 console.log(iterator.next().value); // 2

Example 2: Using a for...of loop

You can easily iterate over the keys using a for...of loop:

let array = ['x', 'y', 'z']; for (let key of array.keys()) { console.log(key); } // Output: // 0 // 1 // 2

Example 3: Converting to an Array

If you want to convert the iterator into an array of keys, you can use Array.from():

let array = [10, 20, 30]; let keysArray = Array.from(array.keys()); console.log(keysArray); // [0, 1, 2]

Example 4: Nested Arrays

The keys() method can be used with nested arrays as well:

let nestedArray = [[1, 2], [3, 4], [5, 6]]; let iterator = nestedArray.keys(); for (let key of iterator) { console.log(key); } // Output: // 0 // 1 // 2

Summary:

  • The keys() method provides a straightforward way to access the indices of elements in an array without needing their values.
  • It returns an iterator, allowing for flexible iteration over the indices in various contexts, such as loops and transformations.
  • This method can simplify code that requires knowledge of the element positions within an array, making it useful for a variety of programming scenarios.