Rose
Rose

Reputation: 2809

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 ?

Upvotes: 1

Views: 867

Answers (3)

Badacadabra
Badacadabra

Reputation: 8497

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));

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386560

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.

Upvotes: 3

FranzKnut
FranzKnut

Reputation: 88

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.

Upvotes: 1

Related Questions