The keys()
method returns a new Array Iterator object that contains the keys for each element in the array.
Example
let alphabets = ["A", "B", "C"];
// returns an Array Iterator object that contains the keys
let iterator = alphabets.keys();
// looping through the Iterator object
for (let key of iterator) {
console.log(key);
}
// Output:
// 0
// 1
// 2
keys() Syntax
The syntax of the keys()
method is:
arr.keys()
Here, arr is an array.
keys() Parameters
The keys()
method does not take any parameters.
keys() Return Value
- Returns a new
Array
iterator object.
Notes: The keys()
method does not:
- change the original array.
- ignore empty array elements.
Example 1: Using keys() Method
let languages = ["JavaScript", "Java", "C++", "Python"];
// returns an Array Iterator Object that contains keys
let iterator = languages.keys();
// looping through the iterator object
for (let key of iterator) {
console.log(key);
}
Output
0 1 2 3
In the above example, we have used the keys()
method to find out the key of each element in the languages array.
Here, languages.keys()
returns an Array Iterator object whose value is stored in iterator.
And finally, we have looped through iterator that prints the key for each element of language.
Example 2: Using key() Method in Array with Holes
The iterator object doesn't skip holes in the array. It also holds the key for empty slots in the array. For example:
let vehicle = ["car", "bus", , "van", "truck"];
// returns an Array Iterator Object that contains keys
let iterator = vehicle.keys();
// looping through the iterator object
for (let key of iterator) {
console.log(key);
}
Output
0 1 2 3 4
Recommended Reading: JavaScript Array values()