JavaScript Reference ยท Array
Array.prototype.entries()
Reference for JavaScript Array.prototype.entries(): get an iterator of [index, value] pairs, loop with for...of and destructuring, and compare with keys() and values().
The entries() method returns a new array iterator object that yields one [index, value] pair for every position in the array, in order. It is most often used in a for...of loop with destructuring, when you need both the index and the value without a classic counter loop.
The iterator is lazy and single use: it produces pairs while you consume it. Use Array.from() or spread to turn it into an array of pairs.
for (const [index, value] of ["a", "b"].entries()) { console.log(index, value); // 0 "a", then 1 "b" }
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
array.entries()
Parameters: none.
Return value: a new iterable iterator object (an "Array Iterator"). Each result's value is a two-element array [index, element] where the index is a number.
Exceptions: none.
Usage notes
- Live view. The iterator reads the array as it goes. Elements added before the iterator finishes are visited, as the
push("z")example shows, and the iterator ends when the index reaches the current length. - Holes are visited and show up as
undefined, unlikeforEach(), which skips them. - Numbers, not strings. Indexes are numbers, whereas
Object.entries(array)returns string keys. - One pass. Once exhausted, the iterator stays done; call
entries()again for a new one. - Siblings:
keys()yields only the indexes,values()only the elements (an array is iterable byvalues()by default, sofor...ofarray uses it). - Break-friendly. Unlike
forEach(), afor...ofloop overentries()supportsbreak,continue,returnandawait. - Arrays only.
MapandSetalso have anentries()method with their own pairs; typed arrays have this one. - Alternative with
map()callbacks: the callback already receives the index as its second argument, so you only needentries()for loops and iterator pipelines.
Browser support
Array.prototype.entries() is supported in every current browser and JavaScript runtime.