Table of Contents
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:
JAVASCRIPTconst 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:
JAVASCRIPTconst 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:
JAVASCRIPTconst 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:
JAVASCRIPTcondition ? valueIfTrue : valueIfFalse;
From here, you can do whatever you want with the value, like setting a new variable:
JAVASCRIPTconst 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:
JAVASCRIPTconst 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:
JAVASCRIPTconst 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.
How to Install Node on Windows, macOS and Linux
Getting Started with Express
How to Serve Static Files with Nginx and Docker
How to Set Up Cron Jobs in Linux
How to deploy a MySQL Server using Docker
Getting Started with Sass
Learn how to use v-model with a custom Vue component
How to Scrape the Web using Node.js and Puppeteer
Getting User Location using JavaScript's Geolocation API
Creating a Twitter bot with Node.js
Using Push.js to Display Web Browser Notifications
Using Axios to Pull Data from a REST API
