Conditional Variable Assignment with the Ternary Operator

Contact Us or call 1-877-932-8228
Conditional Variable Assignment with the Ternary Operator

Conditional Variable Assignment with the Ternary Operator

Sometimes you want to set a variable to a value depending on some condition. You could use an if/else statement, but in many cases the ternary operator is more convenient. [Definition: The ternary operator tests a condition; if the condition is true, it returns a certain value, otherwise it returns a different value.]

The Ternary Operator

// set foo to 1 if bar is true;
// otherwise, set foo to 0
var foo = bar ? 1 : 0;

While the ternary operator can be used without assigning the return value to a variable, this is generally discouraged.

Next