JavaScript Ternary Operator

The funky cousin of the if-else statement

What is the ternary operator?

The JavaScript ternary operator is a magical sprinkling of syntactic sugar that allows you to write concise code. It is a shorthand for the more traditional if-else statement found in JavaScript.

Let's take a look at how we can use it.

Usage

Let's imagine that we have a string literal called meal. You would like to execute some super important conditional logic if meal is equal to Pizza or not.

const meal = "Pizza"

if (team === "Pizza") {
    console.log("Me likey!") // Prints this
} else {
    console.log("Meh!") // Does not get printed
}

Great! The above code snippet will print to the console Me likey! as meal is, in fact, equal to Pizza.

Enter the JavaScript ternary operator.

The ternary operator is the only JavaScript operator that takes three operands. A condition, followed by a question mark, followed by an expression that will be executed if the condition is true, followed by a colon, which is finally followed by an expression that will be executed if the condition was false.

Sounds familiar? That's right, the if-else statement. Let's look at this in code.

const meal = "Pizza"

console.log(team === "Pizza" ? "Me likey!" : "Meh!") // Prints "Me likey!"

Nice! The above code, using the ternary operator, is semantically identical to the code using the if-else statement. With the added benefit of looking much cleaner!

Conclusion

The JavaScript ternary operator is a wonderful way to shorten lines of code and reduces nesting which has the added benefit of making code simpler and easier to read.

Happy coding!

Β