JavaScript entries(): Convert an Array to an Iterator Object

The JavaScript entries() method returns an object Array Iterator that will obviously have key/value pairs. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>
   
   <script>
      const a = ["Berlin", "Vancouver", "Tokyo", "NYC"];

      const b = a.entries();
      
      for(let x of b)
      {
         document.write(x);
         document.write("<BR>");
      }
   </script>
   
</body>
</html>

The snapshot given below shows the sample output produced by the above JavaScript example:

javascript entries

Note: The for...of loop is used to loop through the values of an iterable object.

The code below declares a constant variable a and initializes it with an array of four string elements from the preceding example.

const a = ["Berlin", "Vancouver", "Tokyo", "NYC"];

The entries() function is called on the "a" array, and it returns a new iterator object containing the array's key/value pairs.

const b = a.entries();

To iterate over the b iterator object, a for..of loop is used. The loop variable x is assigned a key/value pair from the iterator object on each iteration.

for(let x of b)
{
   document.write(x);
   document.write("<BR>");
}

The document.write() method is used within the loop to display the current x value on the webpage. The entries() function returns an iterator that provides key/value pairs, resulting in a series of arrays, each containing the index and value of the corresponding element in the "a" array.

JavaScript entries() Syntax

The syntax of the entries() method in JavaScript is:

array.entries()

Advantages of the entries() function in JavaScript

Disadvantages of the entries() function in JavaScript

JavaScript Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!