LoveAndHappiness
LoveAndHappiness

Reputation: 10135

Difference in returning values outside and inside a callback function for a method

I have a method that executes the following function, yet I noticed I can use return in both ways.

Once inside the function:

this.tasks.forEach(function(task) {
    return task.completed = true;
});

Once outside the function:

return this.tasks.forEach(function(task) {
    task.completed = true;
});

Both times I get the correct result, yet I wonder if there is any difference.

Upvotes: 0

Views: 83

Answers (2)

Lucas Ross
Lucas Ross

Reputation: 1089

They're very different but not in a way that necessarily makes any difference in this case. Having return task.completed = true inside the function just has it return true every time, which is ignored by Array.prototype.forEach. The other way, the result of forEach is returned, which is always undefined (it's a void function).

Upvotes: 1

Alexander O'Mara
Alexander O'Mara

Reputation: 60527

As far as the return statement inside the callback function goes, there is no difference, except for the fact that there is an unnecessary return statement in the first example. The return value of the forEach callback function is unused.

However, the return statement outside the callback function could make a functional difference, as it will return undefined in the function it is run in. undefined is the default return value, so you will only notice a difference if there is code after it that is now being skipped. Of course, calling return inside the callback will not return the parent function, as your second example will.

Excerpt from the MDN page on forEach:

forEach() executes the callback function once for each array element; unlike every() and some(), it always returns the value undefined.

Upvotes: 1

Related Questions