Javascript Array entries()

The entries() method returns a new Array Iterator object containing key/value pairs for each array index.

Example

// defining an array named alphabets
const alphabets = ["A", "B", "C"];

// array iterator object that contains // key-value pairs for each index in the array let iterator = alphabets.entries();
// iterating through key-value pairs in the array for (let entry of iterator) { console.log(entry); } // Output: // [ 0, 'A' ] // [ 1, 'B' ] // [ 2, 'C' ]

entries() Syntax

The syntax of the entries() method is:

arr.entries()

Here, arr is an array.


entries() Parameters

The entries() method does not take any parameters.


entries() Return Value

  • Returns a new Array iterator object.

Note: The entries() method does not change the original array.


Example 1: Using entries() Method

// defining an array 
const languages = ["Java", "C", "C++", "Python"];

// array iterator object that contains // key-value pairs for each index in the array let iterator = languages.entries();
// looping through key-value pairs in the array for (let entry of iterator) { console.log(entry); }

Output

[ 0, 'Java' ]
[ 1, 'C' ]
[ 2, 'C++' ]
[ 3, 'Python' ]

In the above example, we have used the entries() method to get an Array iterator object of the key/value pair of each index in the language array.

We have then looped through iterator that prints the key/value pairs of each index.


Example 2: Using next() Method in Array Iterator Object

Array Iterator object has a built-in method called next() which is used to get the next value in the object.

Instead of looping through the iterator, we can get the key/value pairs using next().value. For example:

// defining an array
const symbols = ["#", "$", "*"];

// Array iterator object that holds key/value pairs let iterator = symbols.entries();
// using built-in next() method in Array iterator object console.log(iterator.next().value); console.log(iterator.next().value); console.log(iterator.next().value);

Output

[ 0, '#' ]
[ 1, '$' ]
[ 2, '*' ]

Also Read:

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges