The keys() method of the Array class in JavaScript returns a new array iterator that contains the keys for each index in the calling array.
The syntax of Array.keys() method is:
keys()
This keys() method of Array returns a new array iterator that contains the keys for each index in the calling array.
Array.keys() returns value of type Iterator
.
In JavaScript, we can use the keys() method to iterate over keys in an array.
For example,
const arr = ['apple', 'banana', 'cherry'];
const iterator = arr.keys();
for (const key of iterator) {
console.log(key);
}
0 1 2
We can use destructuring with keys() method to extract keys from the iterator.
For example,
const arr = ['apple', 'banana', 'cherry'];
const iterator = arr.keys();
for (const key of iterator) {
console.log(`Key: ${key}`);
}
Key: 0 Key: 1 Key: 2
In this JavaScript tutorial, we learned about keys() method of Array: the syntax and few working examples with output and detailed explanation for each example.