I am a bit confused why the following two functions are equivalent.
//Function 1
function sumTo(n) {
if (n === 0) return 0; // base case
return n + sumTo(n-1); // inductive step
}
//Function 2
function sumTo(n) {
return n ? n + sumTo(n-1) : 0;
}
In function 2, it uses the conditional operator where the condition is n
. What does the condition n
mean here? My major confusion is that n
is not a boolean value, but why it can be evaluated as True
or False
? Even if it can, with some implicate type casting, where 0
can be interpreted as False
, shouldn't it be return n ? 0 : n + sumTo(n-1)
for the whole thing to make sense?
My guess is that n
means n !== 0
, but it looks so strange.