I am a sys admin trying to learn javascript as the first language. One of the texts I'm learning has this code example in the chapter on recursion.
(variables changed for simplicity)
function fruit(n) {
return n > 1 ? fruit(n - 1) + "apples" : "bananas";
}
I understand the ternary operator aspect of the function, the same could be written like this:
function fruit(n) {
if n > 1
return fruit(n - 1) + "apples";
else
return "bananas";
}
when I call the function, I get the following result
console.log(fruit(3));
bananas apples apples
I don’t understand how the first value is a banana (does this mean that the conditional 3> 1 will be false)? What happens in terms of how this code is executed to come up with this result?
Not sure if this site is friendly, but well in advance for any help.
source
share