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.
Getting Started with TypeScript
Managing PHP Dependencies with Composer
How to Serve Static Files with Nginx and Docker
How to Set Up Cron Jobs in Linux
Best Visual Studio Code Extensions for 2022
How to deploy a PHP app using Docker
How to Scrape the Web using Node.js and Puppeteer
Build a Real-Time Chat App with Node, Express, and Socket.io
Learn how to build a Slack Bot using Node.js
Setting Up Stylus CSS Preprocessor
Getting Started with Vuex: Managing State in Vue
Setting Up a Local Web Server using Node.js
