Tim Tim - 4 months ago 7x
Javascript Question

Javascript ternary operator: What is the condition in "(myvar) ?" when it is a number?

I have a simple Javascript question: What does the following line test on myvar ?

counter = (myvar) ? Math.ceil(counter/myvar) : Math.ceil(counter);

I understand that it is to prevent a division by zero. I googled ternary operators in Javascript, but all I could find were conditions with a comparator (like >, <, etc.)

If it translates to


what does it test ?


Yes, it translates to if(myVar) and means if(0)

0 means false and 1 means true

In your case,

Non-zero: counter = Math.ceil(counter/myvar);

Zero: counter = Math.ceil(counter);

Note: NaN,null,undefined, +0 , -0 and "" are all false too.