JavaScript Array .entries() method

When the array .entries()method is used to an existing array, it creates an Array Iterator that now contains a key/value pair where the keys are the indexes of the reference array and original values are being paired to the corresponding keys.

Array .entries() Method Syntax

This is how you can use the the .entries() method.

    
      const fruits = ["🍉", "🍌", "🍊"];
      const fruitEntries = fruits.entries();

      for (const fruit of fruitEntries) {
        console.log(fruit);
      }
      
      // the output would be:
      // [0, '🍉']
      // [1, '🍌']
      // [2, '🍊']
    
  

Since this method converts a reference array to an array iterator with a key/value pair, make sure that this is the proper approach to your code. An array iterator provides an access to .next() method where it gets the next key/value pair.

Also note that when using the .entries() method, it does not alter or change the original array.

So, continuing with our fruits array as an example above, let's access each array item using the .next() method.

    
      const fruits = ["🍉", "🍌", "🍊"];
      const fruitEntries = fruits.entries();
      
      console.log(fruitEntries.next().value);
      console.log(fruitEntries.next().value);
      console.log(fruitEntries.next().value);
      console.log(fruitEntries.next().value);
      
      // [0, '🍉']
      // [1, '🍌']
      // [2, '🍊']
      // undefined
    
  

You can access the items inside the array iterator object using either a for loop or a .next() method.

Watch: Array .entries() Method Tutorial

Check out this tutorial video for more details about .entries() method in JavaScript.