Home  »  ArticlesGuidesHow ToProgrammingTechnology   »   How to Use The JavaScript Ternary Operator With Examples

How to Use The JavaScript Ternary Operator With Examples

The JavaScript ternary operator also called the conditional operator or Question mark operator is an operator that takes three operands. It is the only JavaScript operator that takes three operands.

It consists of a condition followed by a question mark (?), then an expression to execute if the condition is true followed by a colon (:). Finally, the expression to execute if the condition is false comes thereafter. This operator is frequently used as a shortcut for the if statement.

The following is the syntax of the JavaScript ternary operator:

condition ? value if true : value if false

Let’s take a look at a simple example:

var age = 18;
var transport = (age >= 16) ? "Drive to school" : "Take the bus";

console.log( transport ); // "Drive to school"

Using JavaScript Ternary Operator Conditional Chains

The ternary operator is right-associative, which means it can be “chained”. This is similar to an if … else chain as compared below:

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

The above is equivalent to this:

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

Ref: https://tc39.es/ecma262/#sec-conditional-operator

Found this article interesting? Follow Brightwhiz on Facebook, Twitter, and YouTube to read and watch more content we post.