By Saheb Sutradhar - Updated On 05-03-2024
The JavaScript ternary operator provides a compact way to make decisions based on conditions. It’s often used as an alternative to traditional if...else
statements. Let’s dive into the details of this powerful operator and explore its various use cases.
The basic syntax of the ternary operator:
condition ? exprIfTrue : exprIfFalse
condition
: An expression whose value determines the outcome.exprIfTrue
: An expression executed if the condition evaluates to a truthy value.exprIfFalse
: An expression executed if the condition is falsy.Suppose we want to determine whether someone is old enough to drink. We can use the ternary operator like this:
const age = 20;
const beverage = age >= 21 ? "Beer" : "Juice";
console.log(beverage); // Output: "Juice"
The ternary operator is handy for handling null values. Consider the following function:
const greeting = (person) => {
const name = person ? person.name : "stranger";
return `Howdy, ${name}`;
};
console.log(greeting({ name: "Alice" })); // Output: "Howdy, Alice"
console.log(greeting(null)); // Output: "Howdy, stranger"
You can chain ternary operators to handle more complex scenarios:
function example() {
return condition1 ? value1 : condition2 ? value2 : condition3 ? value3 : value4;
}
This is equivalent to the following if...else
chain:
function example() {
if (condition1) {
return value1;
} else if (condition2) {
return value2;
} else if (condition3) {
return value3;
} else {
return value4;
}
}
Let’s explore more examples of using the JavaScript ternary operator to make your code concise and expressive:
Suppose you have a numeric score, and you want to determine the rating based on whether the score is above 70. Here’s how you can use the ternary operator:
const score = 80;
const scoreRating = score > 70 ? "Excellent" : "Do better";
console.log(scoreRating); // Output: "Excellent"
Imagine you’re building a web application, and you need to decide the next URL based on whether the user is authenticated. The ternary operator can handle this elegantly:
let authenticated = true;
let nextURL = authenticated
? (alert("You will redirect to admin area"), "/admin")
: (alert("Access denied"), "/403");
In this example, if authenticated
is true
, the first expression executes (redirecting to the admin area), otherwise, the second expression executes (showing an access denied message).
Let’s create a function that checks whether a student has passed an exam based on their marks:
const checkPassOrFail = (marks) => (marks >= 40 ? "pass" : "fail");
console.log(checkPassOrFail(78)); // Output: "pass"
console.log(checkPassOrFail(30)); // Output: "fail"
The ternary operator succinctly handles the pass/fail decision.
??
):The nullish coalescing operator distinguishes between:
null
and undefined
.false
, 0
, and an empty string (''
).It returns the right-hand value only if the left-hand value is null or undefined.
Useful for providing default values when dealing with null or undefined variables.
Example:
const x = null;
const y = x ?? 'default'; // y will be 'default'
? :
):The ternary operator checks whether the condition is truthy or falsy.
If the left-hand value is falsy It uses the right-hand value.
Commonly used for conditional expressions.
Example:
const a = 0;
const b = a ? 'truthy' : 'falsy'; // b will be 'falsy'
The JavaScript ternary operator is a powerful tool for concise decision making. Whether you’re handling null values or creating conditional chains, mastering this operator can lead to cleaner and more efficient code. Happy coding! 🚀
Trending Posts
Create Input Floating Label in CSS and HTML...
CSS Card Hover Effects: Make Your Website Stand Ou...
Create a Rotate Image Gallery with HTML and CSS...
CSS Hover Effect | Web Development...
How to create MongoDB Free cloud Database - Atlas ...
Learn how to create CSS Button RGB Animation...
Create Responsive Sidebar with React JS and tailwi...
Build a JavaScript Carousel Slider With Example...
How to Disable the Submit Button in Formik...
How to Use Bootstrap 5 in Next.js...
codelearningpoint © 2024