Reputation: 11
Test of JavaScript function recursion. Unexpected result is test print of string "PRINTS" shows twice in the Firefox console. I don't see how 'return "PRINTS"' is being hit twice.
In stackoverflow's code insert feature I ran the code and it shows PRINTS five times, but Firefox console two times. I am thinking because the line is after the recursive call, that it should only print PRINTS once. There is five recursive calls, why is this getting back to original call five times, the last line of code console.log (isEven(11));
function isEven ( number ) {
if ( number == 0) {
return "even";
}
else if (number == 1) {
return "odd";
}
number = number - 2;
console.log (number);
//the if statements return goes to the recursive call, not outside funct call
console.log(isEven(number));
return "PRINTS";
}
console.log (isEven(11));
Upvotes: 1
Views: 54
Reputation: 2191
You need to return the results of the recursed call back up the chain.
As it is now, here's what your code does:
call isEven(11) ->
11 == 0 false
11 == 1 false
11 - 2 = 9
log(9)
call isEven(9) ->
9 == 0 false
9 == 1 false
9 - 2 = 7
log(7)
call isEven(7) ->
7 == 0 false
7 == 1 false
7 - 2 = 5
log(5)
call isEven(5) ->
5 == 0 false
5 == 1 false
5 - 2 = 3
log(3)
call isEven(3) ->
3 == 0 false
3 == 1 false
3 - 2 = 1
log(1)
call isEven(1) ->
1 == 0 false
1 == 1 true
return "odd"
log("odd")
return "PRINTS"
log("PRINTS")
return "PRINTS"
log("PRINTS")
return "PRINTS"
log("PRINTS")
return "PRINTS"
log("PRINTS")
return "PRINTS"
log("PRINTS")
All those `return "PRINTS" are not the droids you're looking for.
The actual code change is left as an exercise for the reader.
Upvotes: 3