Skip to content
Tutorials Center
My learning

Topics

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.

JavaScript
for (const [index, value] of ["a", "b"].entries()) {
  console.log(index, value); // 0 "a", then 1 "b"
}

Try it

JS Index and value together

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS The iterator itself

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
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, unlike forEach(), 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 by values() by default, so for...of array uses it).
  • Break-friendly. Unlike forEach(), a for...of loop over entries() supports break, continue, return and await.
  • Arrays only. Map and Set also have an entries() 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 need entries() for loops and iterator pipelines.

Browser support

Array.prototype.entries() is supported in every current browser and JavaScript runtime.