We have already covered several methods regarding arrays in JavaScript. Today we are going to speak about the array entries method in JavaScript.
The entries()
method returns a new Array Iterator object that contains the key/value pairs for each index in the array, as per MDN. What does this mean? It means that an entries()
method will return an Object
that will store an index as a key
and a value as a pair
.
Let’s take a look at an example.
const arr = ['Audi', 'BMW', 'Ferrari']; const iterator = arr.entries(); console.log(iterator.next().value); //Result: //[0, 'Audi'] console.log(iterator.next().value); //Result: //[1, 'BMW']
We had an array and then we created another variable and assigned arr.entries()
. After that we used .next()
function. Since .next()
returns Object
with two properties value
(where values are stored) and done
, we, additionally, passed the value property.
Loop through Array Entries
Usually reading value after a value is not that efficient. We need some kind of iterating to make it more efficient.
There are several ways we can loop through Array Entries.
const arr = ['Audi', 'BMW', 'Ferrari']; const iterator = arr.entries(); for (const [index, element] of iterator) { console.log(index, element); } //Result: /** * 0 'Audi' * 1 'BMW' * 2 'Ferrari' * */
In the example above we have used for...of
loop. We used const
keyword and passed index
and element
(Array destructuring). The index
will hold key
inside a loop, while element
will hold a value
. The problem/advantage with this approach is that we can’t change data inside a loop, since we used const
. In order to avoid that we can exclude const
like in the example below.
const arr = ['Audi', 'BMW', 'Ferrari']; const iterator = arr.entries(); for ([index, element] of iterator) { if (index === 1) { element = 'Audi is better'; } console.log(index, element); } //Result: /** * 0 'Audi' * 1 'Audi is better' * 2 'Ferrari' * */
Since we excluded const
keyword we could change data. As we can see, on index 1
in an array was 'BMW'
. But, in the loop, we made the condition that when index
is 1
that value should be changed to 'Audi is better'
.
The third way of looping through array entries is that instead of extracting index
and value
as separate variables, we can extract the entire array instead.
const arr = ['Audi', 'BMW', 'Ferrari']; const iterator = arr.entries(); for (array of iterator) { console.log(array); } //Result: /** * (2) [0, 'Audi'] * (2) [1, 'BMW'] * (2) [2, 'Ferrari'] * */
If you have any questions or anything you can find me on my Twitter, or you can read some of my other articles like How to add the logo to a custom WordPress theme?