Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of array.entries() in javascript?

I'm having trouble understanding why array.entries exists if arrays themselves are iterables?

If I can use a iterable consumer with a simple array (e.g., [1, 2, 3]) then why would it be required to convert an array to an array iterator?

I can't think of any examples where this function would be useful in the real world. Please could someone provide an example of where array.entries() might be used and why?

like image 870
John Avatar asked Oct 31 '25 15:10

John


2 Answers

The method Array.prototype.entries() allows you to use an Iterator object, like you already pointed out correctly.

The major aspect is that you can use e.g. the .next() method. You can read more about iterators and iterables in the MDN JavaScript documentation. This is especially useful if you want to cycle through an array without using a loop.

It also opens you the possibility to make an infinite iterator like this:

var ids = {
  *[Symbol.iterator]: function () {
    var index = 0;

    return {
      next: function () {
        return { value: 'id-' + index++, done: false };
      }
    };
  }
};

var counter = 0;

for (var value of ids) {
  console.log(value);

  if (counter++ > 1000) { // let's make sure we get out!
    break;
  }
}

Source

like image 67
ˈvɔlə Avatar answered Nov 02 '25 06:11

ˈvɔlə


The most important aspect of using an iterator object is that you have more control over the looping of the iterator object.

Example You have an array

let userName = ["John", "Sam", "Michael"];

You wanted to show the user only the first userName at the start (John), but after that, you provide functionality where the user would click on the button which shows the next username(Sam).

So if it is an iterator object you have .next() method, which can be called on each user click and provide a value next in the interation, since it would remember the previous pointer.

let iteratorUserName = userName.entries();

Button where the user would click

button.onclick = () => {
  let nextUserName = iteratorUserName.next();
  if(!nextUserName.done) {
    return nextUserName.value;
  } else {
      alert("No User");
    }
}
like image 35
Rakesh Jain Avatar answered Nov 02 '25 05:11

Rakesh Jain