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 Solid
Getting Started with Svelte
Getting Started with Express
Create an RSS Reader in Node
How to build a Discord bot using TypeScript
Getting Started with Deno
How to deploy an Express app using Docker
Learn how to use v-model with a custom Vue component
Using Puppeteer and Jest for End-to-End Testing
How to Scrape the Web using Node.js and Puppeteer
Getting Started with Moment.js
Setting Up Stylus CSS Preprocessor
