Conditional Operator

The conditional (ternary) operator is the only JavaScript operator that takes three operands. This operator is frequently used as a shortcut for the if statement.


condition ? exprT : exprF 


An expression whose value is used as a condition.
exprT, exprF
Expressions with values of any type.


If condition can be converted to true (it is truthy), the operator returns the value of exprT; otherwise (when condition is falsy) it returns the value of exprF.

(In either case, the other alternative expression is left unevaluated.)

Besides false, possible falsy expressions are: null, NaN, 0, the empty string (""), and undefined. If condition is any of these, the result of the conditional expression will be exprF.

A simple example:

var age = 26;
var beverage = (age >= 21) ? "Beer" : "Juice";
console.log(beverage); // "Beer"

One common usage is to handle a value that may be null:

function greeting(person) {
    var name = person ? person.name : "stranger";
    return "Howdy, " + name;

console.log(greeting({name: 'Alice'}));  // "Howdy, Alice"
console.log(greeting(null));             // "Howdy, stranger"​​​​​

Conditional chains

The ternary operator is right-associative, which means it can be "chained" in the following way, similar to an if … else if … else if … else chain:

function example(…) {
    return condition1 ? value1
         : condition2 ? value2
         : condition3 ? value3
         : value4;

// Equivalent to:

function example(…) {
    if (condition1) { return value1; }
    else if (condition2) { return value2; }
    else if (condition3) { return value3; }
    else { return value4; }


Browser compatibilityUpdate compatibility data on GitHub

Chrome Edge Firefox Internet Explorer Opera Safari
Basic support Yes Yes 1 Yes Yes Yes
Android webview Chrome for Android Edge Mobile Firefox for Android Opera for Android iOS Safari Samsung Internet
Basic support Yes Yes Yes 4 Yes Yes Yes
Basic support Yes

See also

© 2005–2018 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.