Ternary Operator

The ternary operator is an incredibly useful and more concise way of writing your if-else statements.

Ternary Operator

The Ternary Operator

Also known as the conditional operator, the ternary operator is a handy way to write conditional statements.

ter·na·ry

/ˈtərnərē/
adjective
composed of three parts

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.

Syntax

condition ? ifExpressionTrue : ifExpressionFalse

The syntax is rather straight forward, albeit a little strange to look at. To use a ternary operator, you need to pass in a condition and if the expression evaluates to true, it returns ifExpressionTrue, otherwise it returns ifExpressionFalse.

Real World Example 🌎

First let's take a look at a traditional if-else statement, then we will refactor the code to use the ternary operator.

Traditional if-else statement

Here's some code for a conditional greeting that gets shown to the user depending on whether or not they are currently logged into our web app. We use an if-else statement to determine if they're logged in, and if so, we return a more personalized greeting to them. If not, we return a generic greeting to them.

const user = { 

    username: "timwheelercom",
    
    isLoggedIn: true
    
}


const greetUser = (user) => {
    
    if (user.isLoggedIn) {

        return `Good Morning, ${user.username}!`;

    } else {

        return "Good Morning!";

    }
}

greetUser(user);

Try this the code snippet in your browser console.

Using the ternary operator

Here get rid of that bloated if-else statement and replace it with a slick, concise ternary operator that will function exactly the same way but is ultimately more readable.

const user = { 

    username: "timwheelercom",
    
    isLoggedIn: true
    
}

const greetUser = (user) => {
    
    return user.isLoggedIn ? `Good Morning, ${user.username}!` : "Good Morning!";
}

greetUser(user);

Try this the code snippet in your browser console.

Wrapping Up ✅

The ternary operator is a great way to tighten up your code and make it more readable for others. Give it a shot and let me know what you think!

Stay Tuned 📺

If you have any questions or improvements, or if you'd like to see additional examples, feel free to reach out to me anytime at [email protected]. If you're enjoying my posts, please subscribe below! 👇

Help us improve our content