Looking for help with this nested ternary operator. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Looking for help with this nested ternary operator.

Hi, I just can't wrap my head around this one challenge question from JavaScript. function f(a) { return a > 0 ? 0 && 1 ? 1 : 0 : 1; } console.log(f(0)); //Output: 1 console.log(f(1)); //Output: 0 console.log(f(2)); //Output: 0 Can someone explain what is happening here?

11th Jul 2018, 7:18 PM
Jonas
Jonas - avatar
3 Answers
+ 2
For me it always helps splitting the view in outer and inner part. The outer part is easy: if a > 0 do inner part else return 1. Now the inner part: if 0 && 1 do return 1 else return 0. However, 0 && 1 is always false, so whenever this is executed, 0 will be returned. As to the function calls: In the first call, the outer condition is false, therefore 1 is returned. For the other calls, the outer part evaluates to true, the inner part is executed, which returns 0 anyway, therefore they print 0.
11th Jul 2018, 7:24 PM
Shadow
Shadow - avatar
+ 1
Thanks, Naitomea. Now this seems rather clear. Basically I can just wrap inner part into parentheses. function f(a) { return a > 0 ? ((0 && 1) ? 1 : 0) : 1; } At first I somehow assumed && meant double check like a > 0 and a > 1, but it was just (false && true) condition.
11th Jul 2018, 7:36 PM
Jonas
Jonas - avatar
+ 1
Yes, wrapping the inner part into parentheses is a good idea because it aids the readability. I've done that a lot lately.
11th Jul 2018, 7:40 PM
Shadow
Shadow - avatar