JavaScript in 60 Seconds

Conditional (ternary) operator

You’ve met if statements. Conditional operators (often referred to as ternay operators work similarly to if-else statements.

What is a ternary operator?

A ternary operator is basically an if-else statement with more concise syntax.

Here’s the basic stucture:

condition ? trueExpression : falseExpression;

What’s happening

If the condition is true, it will run the trueExpression (between ? and :). If the condition is false, it will run the falseExpression (to the right of :).

Now a concrete example:

var message = 3 > 5 ? '3 IS greater than 5': '3 is NOT greater than 5'; console.log(message);

Let’s compare ternary and if-else:

// version a) var message = 3 > 5 ? '3 IS greater than 5': '3 is NOT greater than 5'; // version b) var message; if (3 > 5) { message = '3 IS greater than 5'; } else { message = '3 is NOT greater than 5'; }

The nice thing with ternary operators is that you can assign the result of the statement to a variable in a concise manner.

Downsides

I generally only use ternary operators for very simple conditionals. For anything more complicated I use if-else statements.