Javascript - Array entries() Method

The entries() method returns an Array Iterator object with key/value pairs.

Description

The entries() method returns an Array Iterator object with key/value pairs.

For each item in the original array, the iteration object contains an array with the index as the key, and the item value as the value:

[0, "XML"][1, "Json"][2, "Database"][3, "Mango"]

Syntax

array.entries()

Parameter Values

No parameters.

Return

An Array Iterator object

Example

Create an Array Iterator object, with key/value pairs for each item in the array:

Demo

var myArray = ["XML", "Json", "Database", "Mango"];
var x = myArray.entries();
console.log( x.next().value);

Result

The entries() method returns a sequence of values as an iterator.

An iterator provides a next() method that returns the next item in the sequence.

The next() method returns an object with two properties:

  • done, a Boolean that is true when all the elements of the iterable have been iterated over
  • value, represents the item in the collection .

Every iterable must implement the iterable protocol, meaning that the object must have a property with a Symbol.iterator key.

const arr = [11,12,13]; 
const itr = arr[Symbol.iterator](); 

itr.next(); // { value: 11, done: false } 
itr.next(); // { value: 12, done: false } 
itr.next(); // { value: 13, done: false } 

itr.next(); // { value: undefined, done: true } 

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

Demo

const breakfast = ['XMLs', 'Screens', 'Keyboards']; 
const eBreakfast = breakfast.entries(); 

console.log(eBreakfast.next().value); // [0, 'XMLs'] 
console.log(eBreakfast.next().value); // [1, 'Screens'] 
console.log(eBreakfast.next().value); // [2, 'Keyboards']

Result

You can use a for-of loop to iterate over the iterator returned from the breakfast.entries() call:

for (let entry of eBreakfast) { 
    console.log(entry); 
} 
// [0, 'XMLs'] 
// [1, 'Screens'] 
// [2, 'Keyboards']