Reputation: 10135
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
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
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.
forEach
:
forEach()
executes thecallback
function once for each array element; unlikeevery()
andsome()
, it always returns the valueundefined
.
Upvotes: 1