The JavaScript Array keys() method returns a new array iterator object that contains the keys (indices) for each element in the array. This method is useful when you need to loop over the indices of an array rather than its elements.
For example, array.keys() is helpful when you need to iterate over the indices in a for…of loop or access keys directly.
Syntax
The syntax for the Array.keys() method is:
array.keys()
Parameters
The Array.keys() method does not accept any parameters.
Return Value
It returns a new array iterator object that contains the keys (indices) of the array elements.
Examples of JavaScript Array.keys() Method
Example 1: Using keys() to Iterate Over Array Indices
You can use the Array.keys() method with a for...of loop to iterate over the indices of an array.
const fruits = ['apple', 'banana', 'mango'];
const keys = fruits.keys();
for (let key of keys) {
console.log(key);
}
// Output: 0 1 2
Explanation: The keys() method returns an iterator object containing the indices of the fruits array, which are then logged in a for...of loop.
Example 2: Accessing Indices Directly with keys()
You can manually retrieve the keys (indices) from the iterator using the next() method.
const fruits = ['apple', 'banana', 'mango'];
const keysIterator = fruits.keys();
console.log(keysIterator.next().value); // Output: 0
console.log(keysIterator.next().value); // Output: 1
console.log(keysIterator.next().value); // Output: 2
Explanation: The keysIterator.next().value expression retrieves each key (index) from the iterator object in sequence.
Example 3: Working with Sparse Arrays
The keys() method can also be used with sparse arrays (arrays with empty or undefined elements).
const sparseArray = [10, , 30];
const keys = sparseArray.keys();
for (let key of keys) {
console.log(key);
}
// Output: 0 1 2
Explanation: The keys() method returns the indices for all elements, including those that are empty or undefined, without skipping any indices.
Example 4: Converting keys() Iterator to an Array
You can use the Array.from() method to convert the iterator returned by keys() into an array of indices.
const numbers = [100, 200, 300];
const keysArray = Array.from(numbers.keys());
console.log(keysArray); // Output: [0, 1, 2]
Explanation: The Array.from() method converts the iterator returned by keys() into an array of the indices [0, 1, 2].
Example 5: Combining keys() with Array Elements
You can use keys() to access both the indices and the corresponding values of an array.
const fruits = ['apple', 'banana', 'mango'];
const keys = fruits.keys();
for (let key of keys) {
console.log(`Index: ${key}, Value: ${fruits[key]}`);
}
// Output:
// Index: 0, Value: apple
// Index: 1, Value: banana
// Index: 2, Value: mango
Explanation: The keys() method is used to retrieve the indices of the array, and then each index is used to access the corresponding element in the array.