How to use the JavaScript Ternary Operator

Updated onbyAlan Morel
How to use the JavaScript Ternary Operator

In this post, you will learn about the JavaScript ternary operator and how to use it to improve your code.

JavaScript Ternary Operator

The JavaScript ternary operator is a shorthand for an if/else statement. Let's look at a traditional if/else block:

const cost = 10;
const money = 5;

if (cost > money) {
    console.log("You need more money");
} else {
    console.log("You can buy this");
}

You can convert this to equivalent ternary operator code:

const cost = 10;
const money = 5;

console.log(cost > money ? "You need more money" : "You can buy this");

Alternatively, you can use the ternary operator to set a new variable:

const cost = 10;
const money = 5;

const message = cost > money ? "You need more money" : "You can buy this";

console.log(message);

In general, the syntax for ternary operators is as follows:

condition ? valueIfTrue : valueIfFalse;

From here, you can do whatever you want with the value, like setting a new variable:

const result = condition ? valueIfTrue : valueIfFalse;

Handle null and undefined

You can use the ternary operator to gracefully handle null and undefined values. For example, you can use the ternary operator to set a variable to a default value if the value is null:

const fruit = null;

const defaultFruit = "apple";
const result = fruit ? fruit : defaultFruit;

console.log(result); // apple

Chain Ternary Operators

You can even use multiple ternary operators in a chain, also known as nesting ternary operators, to check for more than one condition:

const fruit = null;
const fruit2 = "banana";

const defaultFruit = "apple";
const result = fruit ? fruit : (fruit2 ? fruit2 : defaultFruit);

console.log(result); // banana

In this example, we're checking for fruit and then fruit2 to be null. If both are null, we'll use the default value of apple.

Conclusion

In this post, we've learned how to use the JavaScript ternary operator to improve your code. We've learned how to use it to gracefully handle null values and how to chain multiple ternary operators together.

Hopefully, this post has helped you learn about the JavaScript ternary operator and how to use it to write more concise code.

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.