简体   繁体   中英

foreach loop syntax in javascript

Consider myArray as an array of objects.

Are these two pieces of code equivalent ?

myArray.forEach((item) => {
  return doAnAction(item);
});


myArray.forEach((item) => {
      doAnAction(item);
    });

Is there any of them that is better in terms of syntax? If yes, why ?

The better question is, why you do not use the function directly as callback, like

myArray.forEach(doAnAction);

The callback must follow the API of Array#forEach , which is

Function to execute for each element, taking three arguments:

  • currentValue : The current element being processed in the array.
  • index : The index of the current element being processed in the array.
  • array : The array that forEach() is being applied to.

If you need only the element, then you could use the given callback directly without any mapping.

As I understand there's no difference between these two because you are providing an anonymous function to be applied to each element in the Array whereas the first one does return the result of doAnAction(item) (which is ignored anyway) and the second one does not.

So they are really equivalent, the second just makes more sense to me for the intended meaning.

This is not specific to the forEach loop. It is just ES6 syntax.

With ES5, here is the right syntax:

myArray.forEach(function (item) {
  doAnAction(item);
});

With ES6, you have more possibilities:

// Solution #1
myArray.forEach((item) => {
  doAnAction(item);
});

// Solution #2
myArray.forEach(item => {
  doAnAction(item);
});

// Solution #3
myArray.forEach(item => doAnAction(item));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM