+ 1
Ternary operator and recursion interaction question
Hi this in JavaScript: function recursion(n) { if(n===1){ return 2; } return n * recursion(n-1); }; console.log(recursion(3)); Is equivalent to that: function rec(n) { return n ? (n * rec(n-1)) : 2; }; console.log(rec(3)); I understand why the recursion total gets multiplied by the if statement return in the first example But I can't wrap my head around why is it getting multiplied by the third operand in ternary operator in second example. Shouldn't it get ignored as falsy? Or if not shouldn't the second operand get ignored as truthy? How does the computer read the second example step by step?
2 Respostas
+ 2
The second function is equivalent to:
function rec(n) {
if (n) {
return n*(rec(n-1));
}
return 2;
};
"if (n)" is False when n==0.
rec(3)
== rec(2)*(3)
== rec(1)*2*3
== rec(0)*1*2*3 // "if n" is False
== 2*1*2*3
== 12.
+ 1
Ah thank you for explanation. I was under the impression that one of the operands on either side of : gets ignored and then only one of them gets used.