Array.prototype.entries()

The entries() method returns a new array iterator object that contains the key/value pairs for each index in the array.

Try it

Syntax

entries()

Return value

Description

When used on sparse arrays, the entries() method iterates empty slots as if they have the value undefined.

The entries() method is generic. It only expects the this value to have a length property and integer-keyed properties.

Examples

Iterating with index and element

const a = ["a", "b", "c"];

for (const [index, element] of a.entries()) {
  console.log(index, element);
}

// 0 'a'
// 1 'b'
// 2 'c'

Using a for...of loop

const array = ["a", "b", "c"];
const arrayEntries = array.entries();

for (const element of arrayEntries) {
  console.log(element);
}

// [0, 'a']
// [1, 'b']
// [2, 'c']

Iterating sparse arrays

entries() will visit empty slots as if they are undefined.

for (const element of [, "a"].entries()) {
  console.log(element);
}
// [0, undefined]
// [1, 'a']

Calling entries() on non-array objects

The entries() method reads the length property of this and then accesses each integer index.

const arrayLike = {
  length: 3,
  0: "a",
  1: "b",
  2: "c",
};
for (const entry of Array.prototype.entries.call(arrayLike)) {
  console.log(entry);
}
// [ 0, 'a' ]
// [ 1, 'b' ]
// [ 2, 'c' ]

Specifications

Specification
ECMAScript Language Specification
# sec-array.prototype.entries

Browser compatibility

BCD tables only load in the browser

See also