+ 1

JavaScript a>0?0&&1?1:0:1;

What does this tricky ternary operator mean? Why does it contain two question marks? I have found this code in a SL challenge and as a beginner in js, I would like to learn from it. function f(a) { return a>0?0&&1?1:0:1; } alert(f(1))

2nd Feb 2020, 6:28 AM
Prof. Dr. ZoltĂĄn Vass
3 Answers
+ 8
A ternary operator has a condition, if it evaluates to true then one after the ? is executed else one after the : is executed. Divide it like this- return a>0? { 0&&1?1:0 } :1; If a>0 is true then the one inside the { } will execute and if it is false then it returns 1. So 1>0 is true and inside { } again perform similar operation, so 0&&1 is false, so it will return 0.
2nd Feb 2020, 6:50 AM
Avinesh
Avinesh - avatar
+ 3
So there is an embedded ternary operator in the outer one. Thanks Avinesh ~ swim ~ !
2nd Feb 2020, 7:36 AM
Prof. Dr. ZoltĂĄn Vass