Reputation: 43
I have been playing with the code above and still don't know why is it behaving like this:
function myforEach(arr, func){
for(var i=0; i<arr.length; i++){
func();
}
}
var arr = [1,2,3];
function func2(){
return 3+3;
}
myforEach(arr, func2); // undefined
I create a myforEach function which takes two arguments an array and a function passed as an argument func, which is called below within the for loop 3 times. Then i declare another function func2 which returns the value of adding 3+3.
Then i run the myforEach
with the two arguments and i expect to print in the console 3 times the value 6, however what is being returned is undefined.
When i change the func2 statement to:
function func2(){
console.log(3+3);
}
and run again i get console logged 6 three times. myforEach(arr, func2); // (3)6
Then i change again the func2 statement to:
function func2(){
console.log("hi");
}
myforEach(arr, func2); // (3)hi
If Try myforEach(arr, alert); // (3)alert
however if i try to put alert within func2 without parenthesis function func2(){alert;} // undefined
but when adding parenthesis function func2(){alert();}
then it alerts three times
So the question is why is the function func2(){return 3+3;}
not returning 6 three times? Since within the for loop the func() is in parentheses means any function added is invoked why is not the func2 being invoked properly?
I made some research on stackoverflow but all i could get was the return for some reason gets lost but no further detailed explanation to the why and root cause.
Is late here and i don't know if i am missing something or just too sleepy. Any explanation would be helpful. Thanks :)
Upvotes: 1
Views: 55
Reputation: 1562
The function is returning 6
as expected. you need a means to contain that returned value. if you assign the invocation func2()
to any variable, its value will be 6
Upvotes: 0
Reputation: 1074959
So the question is why is the function func2(){return 3+3;} not returning 6 three times?
It is — you're just not doing anything with that return value. You're passing func2
into myforEach
and receiving it as func
, but then:
function myforEach(arr, func){
for(var i=0; i<arr.length; i++){
func(); // <=== You're not using the return value for anything
}
}
Just returning the value doesn't cause it to be output automatically anywhere.
Note that this would be the case with the built-in forEach
as well:
console.log("Nothing gets output after this message");
var arr = [1,2,3];
function func2(){
return 3+3;
}
arr.forEach(func2);
forEach
is intentionally bland, it does nothing with the return value of the function you give it. It doesn't remember it anywhere (that would be map
), output it, sum it up with others (that would be reduce
, effectively), etc. Your myforEach
is similarly bland.
Upvotes: 2