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
Getting Started with Svelte
Create an RSS Reader in Node
Getting Started with Electron
How to deploy a .NET app using Docker
How to deploy a PHP app using Docker
How to deploy a MySQL Server using Docker
How to deploy an Express app using Docker
How to Scrape the Web using Node.js and Puppeteer
Creating a Twitter bot with Node.js
Getting Started with React
How To Create a Modal Popup Box with CSS and JavaScript
