JavaScript Array keys()
Syntax & Examples
Array.keys() method
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.
Syntax of Array.keys()
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.
Return Type
Array.keys() returns value of type Iterator
.
✐ Examples
1 Using keys() method to iterate over keys
In JavaScript, we can use the keys() method to iterate over keys in an array.
For example,
- We define an array variable arr with elements ['apple', 'banana', 'cherry'].
- We create an iterator using the keys() method on arr.
- We use a for...of loop to iterate over each key in the iterator.
- Inside the loop, we log each key to the console.
JavaScript Program
const arr = ['apple', 'banana', 'cherry'];
const iterator = arr.keys();
for (const key of iterator) {
console.log(key);
}
Output
0 1 2
2 Using keys() method with destructuring
We can use destructuring with keys() method to extract keys from the iterator.
For example,
- We define an array variable arr with elements ['apple', 'banana', 'cherry'].
- We create an iterator using the keys() method on arr.
- We use destructuring to extract keys from the iterator in a for...of loop.
- Inside the loop, we log key to the console.
JavaScript Program
const arr = ['apple', 'banana', 'cherry'];
const iterator = arr.keys();
for (const key of iterator) {
console.log(`Key: ${key}`);
}
Output
Key: 0 Key: 1 Key: 2
Summary
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.