Quick Tip: How to Use the Ternary Operator in JavaScript

    Dianne Pena
    Share

    In this tutorial, we’ll explore the syntax of the ternary operator in JavaScript and some of its common uses.

    The ternary operator (also known as the conditional operator) can be used to perform inline condition checking instead of using if...else statements. It makes the code shorter and more readable. It can be used to assign a value to a variable based on a condition, or execute an expression based on a condition.

    Syntax

    The ternary operator accepts three operands; it’s the only operator in JavaScript to do that. You supply a condition to test, followed by a questions mark, followed by two expressions separated by a colon. If the condition is considered to be true (truthy), the first expression is executed; if it’s considered to be false, the final expression is executed.

    It’s used in the following format:

    condition ? expr1 : expr2
    

    Here, condition is the condition to test. If its value is considered to be true, expr1 is executed. Otherwise, if its value is considered to be false, expr2 is executed.

    expr1 and expr2 are any kind of expression. They can be variables, function calls, or even other conditions.

    For example:

    1 > 2 ? console.log("You are right") : console.log('You are wrong');
    

    Using the Ternary Operator for Value Assignment

    One of the most common use cases of ternary operators is to decide which value to assign to a variable. Often, a variable’s value might depend on the value of another variable or condition.

    Although this can be done using the if...else statement, it can make the code longer and less readable. For example:

    const numbers = [1,2,3];
    let message;
    if (numbers.length > 2) {
      message = 'The numbers array is too long';
    } else {
      message = 'The numbers array is short';
    }
    
    console.log(message); // "The numbers array is too long"
    

    In this code example, you first define the variable message. Then, you use the if...else statement to determine the value of the variable.

    This can be simply done in one line using the ternary operator:

    const numbers = [1,2,3];
    let message = numbers.length > 2 ? 'The numbers array is too long' : 'The numbers array is short';
    
    console.log(message); // "The numbers array is too long"
    

    Using the Ternary Operator for Executing Expressions

    Ternary operators can be used to execute any kind of expression.

    For example, if you want to decide which function to run based on the value of a variable, you can do it like this using the if...else statement:

    if (feedback === "yes") {
      sayThankYou();
    } else {
      saySorry();
    }
    

    This can be done in one line using the ternary operator:

    feedback === "yes" ? sayThankYou() : saySorry();
    

    If feedback has the value yes, then the sayThankYou function will be called and executed. Otherwise, the saySorry function will be called and executed.

    Using the Ternary Operator for Null Checks

    In many cases, you might be handling variables that may or may not have a defined value — for example, when retrieving results from user input, or when retrieving data from a server.

    Using the ternary operator, you can check that a variable is not null or undefined just by passing the variable name in the position of the condition operand.

    This is especially useful when the variable is an object. If you try to access a property on an object that’s actually null or undefined, an error will occur. Checking that the object is actually set first can help you avoid errors.

    For example:

    let book = { name: 'Emma', author: 'Jane Austen' };
    console.log(book ? book.name : 'No book'); // "Emma"
    
    book = null;
    console.log(book ? book.name : 'No book'); // "No book"
    

    In the first part of this code block, book is an object with two properties — name and author. When the ternary operator is used on book, it checks that it’s not null or undefined. If it’s not — meaning it has a value — the name property is accessed and logged into the console. Otherwise, if it’s null, No book is logged into the console instead.

    Since book is not null, the name of the book is logged in the console. However, in the second part, when the same condition is applied, the condition in the ternary operator will fail, since book is null. So, “No book” will be logged in the console.

    Nested Conditions

    Although ternary operators are used inline, multiple conditions can be used as part of a ternary operator’s expressions. You can nest or chain more than one condition to perform condition checks similar to if...else if...else statements.

    For example, a variable’s value may depend on more than one condition. It can be implemented using if...else if...else:

    let score = '67';
    let grade;
    if (score < 50) {
      grade = 'F';
    } else if (score < 70) {
      grade = 'D'
    } else if (score < 80) {
      grade = 'C'
    } else if (score < 90) {
      grade = 'B'
    } else {
      grade = 'A'
    }
    
    console.log(grade); // "D"
    

    In this code block, you test multiple conditions on the score variable to determine the letter grading of the variable.

    These same conditions can be performed using ternary operators as follows:

    let score = '67';
    let grade = score < 50 ? 'F'
      : score < 70 ? 'D'
      : score < 80 ? 'C'
      : score < 90 ? 'B'
      : 'A';
    
    console.log(grade); // "D"
    

    The first condition is evaluated, which is score < 50. If it’s true, then the value of grade is F. If it’s false, then the second expression is evaluated which is score < 70.

    This keeps going until either all conditions are false, which means the grade’s value will be A, or until one of the conditions is evaluated to be true and its truthy value is assigned to grade.

    CodePen Example

    In this live example, you can test how the ternary operator works with more multiple conditions.

    If you enter a value less than 100, the message “Too Low” will be shown. If you enter a value greater than 100, the message “Too High” will be shown. If you enter 100, the message “Perfect” will be shown.

    See the Pen
    Ternary Operator in JS
    by SitePoint (@SitePoint)
    on CodePen.

    Conclusion

    As explained in the examples in this tutorial, the ternary operator in JavaScript has many use cases. In many situations, the ternary operator can increase the readability of our code by replacing lengthy if...else statements.

    Related reading: