JavaScript Array keys() method returns a new Array Iterator object containing the keys (or indices) of the elements in the array. It is particularly useful for iterating over an array’s indices.

Pre-requisites to Learn
Syntax
arr.keys();
Parameters
The Array.keys() method does not accept any parameters.
Return Value
The keys() method returns a new Array Iterator object that contains the indices (keys) of the array elements. The iterator can be used in loops or converted into an array.
Notes:
- This method does not modify the original array.
- This method returns the indices of the array.
Examples of JavaScript Array keys() Method
Example 1: The keys() method returns an iterator that can be used to loop through the indices of the array.
let arr = ['apple', 'banana', 'cherry']; let keysIterator = fruits.keys(); for (let key of keysIterator) { console.log(key); } // Output: // 0 // 1 // 2
Example 2: This method combined with Array.from() method to create an array of indices.
let arr = [10, 20, 30, 40]; let keysArray = Array.from(arr.keys()); console.log(keysArray); // Output: [0, 1, 2, 3]
Example 3: Using keys() with Sparse Arrays – the second element is missing, its index (1
) is still included in the keys.
let sparseArray = [10, , 30, 40]; let keysIterator = sparseArray.keys(); for (let key of keysIterator) { console.log(key); } // Output: // 0 // 1 // 2 // 3
Example 4: The keys() method can be combined with map() or other methods for advanced processing.
let arr = ['apple', 'banana', 'cherry']; let keyValues = arr.keys(); let result = Array.from(keyValues).map(key => `Index: ${key}`); console.log(result); // Output: ['Index: 0', 'Index: 1', 'Index: 2']
Supported Browsers
Browser | Support |
---|---|
Chrome | 38+ |
Firefox | 32+ |
Safari | 8+ |
Edge | 12+ |
Opera | 25+ |
Internet Explorer | Not supported |
Comparison with Other Methods
Method | Purpose |
---|---|
Array.keys() Method | Returns an iterator of array indices (keys). |
Array.values() Method | Returns an iterator of array values. |
Array.entries() Method | Returns an iterator of [index, value] pairs. |