JavaScript Array entries()
Syntax & Examples
Array.entries() method
The entries() method of the Array class in JavaScript returns a new array iterator object that contains the key/value pairs for each index in the array.
Syntax of Array.entries()
The syntax of Array.entries() method is:
entries()
This entries() method of Array returns a new array iterator object that contains the key/value pairs for each index in an array.
Return Type
Array.entries() returns value of type Iterator
.
✐ Examples
1 Using entries() method to iterate over key/value pairs
In JavaScript, we can use the entries() method to iterate over key/value pairs in an array.
For example,
- We define an array variable arr with elements ['apple', 'banana', 'cherry'].
- We create an iterator using the entries() method on arr.
- We use a for...of loop to iterate over each entry in the iterator.
- Inside the loop, we log each entry to the console.
JavaScript Program
const arr = ['apple', 'banana', 'cherry'];
const iterator = arr.entries();
for (const entry of iterator) {
console.log(entry);
}
Output
[0, 'apple'] [1, 'banana'] [2, 'cherry']
2 Using entries() method with destructuring
We can use destructuring with entries() method to extract key/value pairs from the iterator.
For example,
- We define an array variable arr with elements ['apple', 'banana', 'cherry'].
- We create an iterator using the entries() method on arr.
- We use destructuring to extract key/value pairs from the iterator in a for...of loop.
- Inside the loop, we log key and value to the console.
JavaScript Program
const arr = ['apple', 'banana', 'cherry'];
const iterator = arr.entries();
for (const [key, value] of iterator) {
console.log(`Key: ${key}, Value: ${value}`);
}
Output
Key: 0, Value: apple Key: 1, Value: banana Key: 2, Value: cherry
Summary
In this JavaScript tutorial, we learned about entries() method of Array: the syntax and few working examples with output and detailed explanation for each example.