Ternary operator and recursion interaction question | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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?

5th Feb 2019, 8:40 PM
Harry Sild
Harry Sild - avatar
2 Answers
+ 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.
5th Feb 2019, 11:08 PM
Diego
Diego - avatar
+ 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.
6th Feb 2019, 4:26 AM
Harry Sild
Harry Sild - avatar