• JavaScript Video Tutorials

JavaScript - Array entries() Method



In JavaScript, the Array.entries() method creates a new Array iterator object that retunrs key-value pairs for each index in the specified array. Where, each key-value pair represents an index/value pair. The key is the "index" of the element in the array, and the value is the corresponding array element.

This method does not change or modify the original array; instead, it returns an Array Iterator object with key-value pairs.

Syntax

Following is the syntax of JavaScript Array entries() method −

array.entries();

Parameters

This method does not accept any parameters.

Return value

A new array iterator object that contains key/value pairs for each index in the array.

Examples

Example 1

In the following example, we are using the entries() method to iterate through each element in the array “animals” and prints the index and value as key/value pairs.

<html>
<body>
   <script>
      const animals = ["Lion", "Cheetah", "Tiger", "Elephant", "Dinosaur"];

      for (const i of animals.entries()) {
         document.write(i + "<br>");
      }
   </script>
</body>
</html>

Output

As we can see in the output, the array elements are printed as key/value pairs.

0,Lion
1,Cheetah
2,Tiger
3,Elephant
4,Dinosaur

Example 2

Here, we are iterating through each element in the specified array, destructuring the key (index) and value (animal), and prints them in a formatted string.

<html>
<body>
   <script>
      const animals = ["Lion", "Cheetah", "Tiger", "Elephant", "Dinosaur"];

      for (const [index, animal] of animals.entries()) {
         document.write(`Index: ${index}, Name: ${animal}<br>`);
      }
   </script>
</body>
</html>

Output

As we can see in the output, the array elements are printed as key(index) and value (animal) pairs.

Index: 0, Name: Lion
Index: 1, Name: Cheetah
Index: 2, Name: Tiger
Index: 3, Name: Elephant
Index: 4, Name: Dinosaur
Advertisements