How to Use the Ternary Operator in JavaScript, With Examples

JavaScript Ternary Operator

This short article will explain what the ternary operator is in JavaScript and how to use it.

The ternary operator is a short-hand if statement for quickly executing code based on whether a condition is met.

It simplifies your code and reduces visual clutter.

Here’s how to use it.

JavaScript Ternary Operator Syntax

The syntax for using the ternary operator is as follows:

CONDITION ? TRUE_EXPRESSION : FALSE_EXPRESSION

Note that:

  • CONDITION should be a value or expression which can be evaluated as truthy or not truthy
  • TRUE_EXPRESSION is the expression that will be executed if CONDITION is truthy
  • FALSE_EXPRESSION is the expression that will be executed if CONDITION is not truthy
  • The ? character separates the condition from the expressions, and the : character separates the true/false expressions
  • The whole expression will return the result of evaluation TRUE_EXPRESSION or FALSE_EXPRESSION
    • This can be assigned to a variable, allowing you to assign values to variables conditionally

Ternary Operator Example

Consider this if statement:

var myNumber = 4;
var myText = "";
if(myNumber > 3) {
    myText = "myNumber is greater than 3";
} else {
    myText = "myNumber is less than 3";
}

It sets the value of the myText variable based on the value of myNumber. It’s a lot of code for a relatively simple task.

Here it is again, but this time using a ternary operator instead of an if statement:

var myNumber = 4;
var myText = myNumber > 3 ? "myNumber is greater than 3" : "myNumber is less than 3";

You can see the CONDITION (myNumber > 3), TRUE_EXPRESSION (“myNumber is greater than 3”), and FALSE_EXPRESSION (“myNumber is less than 3”) forming the ternary expression – the result of which is assigned to the variable myText.

The amount of code is greatly reduced, and myText receives the result of the ternary operation as its value.

You can see more examples on the Mozilla Developer Documentation here.

Ternary operators make code more readable – if you have a lot of simple if statements, they can really clean up your code. Just don’t use them if you bill by the number of lines of code you write.

SHARE:
nv-author-image

Brad Morton

I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Reply

Your email address will not be published. Required fields are marked *