On this tutorial, we’ll explore the syntax of the ternary operator in JavaScript and a few of its common uses.
The ternary operator (also often known as the conditional operator) may be used to perform inline condition checking as a substitute of using if…else statements. It makes the code shorter and more readable. It may possibly be used to assign a price to a variable based on a condition, or execute an expression based on a condition.
Syntax
The ternary operator accepts three operands; it’s the one operator in JavaScript to do this. You supply a condition to check, followed by a questions mark, followed by two expressions separated by a colon. If the condition is taken into account to be true (truthy), the primary expression is executed; if it’s considered to be false, the ultimate expression is executed.
It’s utilized in the next format:
condition ? expr1 : expr2
Here, condition is the condition to check. If its value is taken into account to be true, expr1 is executed. Otherwise, if its value is taken into account to be false, expr2 is executed.
expr1 and expr2 are any sort of expression. They may be variables, function calls, and even other conditions.
For instance:
1 > 2 ? console.log(“You’re right”) : console.log(‘You’re improper’);
Using the Ternary Operator for Value Project
One of the vital common use cases of ternary operators is to make your mind up which value to assign to a variable. Often, a variable’s value might rely on the worth of one other variable or condition.
Although this may be done using the if…else statement, it could actually make the code longer and fewer readable. For instance:
const numbers = [1,2,3];
let message;
if (numbers.length > 2) {
message = ‘The numbers array is simply too long’;
} else {
message = ‘The numbers array is brief’;
}
console.log(message);
On this code example, you first define the variable message. Then, you employ the if…else statement to find out the worth of the variable.
This may be simply done in a single line using the ternary operator:
const numbers = [1,2,3];
let message = numbers.length > 2 ? ‘The numbers array is simply too long’ : ‘The numbers array is brief’;
console.log(message);
Using the Ternary Operator for Executing Expressions
Ternary operators may be used to execute any sort of expression.
For instance, if you desire to resolve which function to run based on the worth of a variable, you may do it like this using the if…else statement:
if (feedback === “yes”) {
sayThankYou();
} else {
saySorry();
}
This may be done in a single line using the ternary operator:
feedback === “yes” ? sayThankYou() : saySorry();
If feedback has the worth yes, then the sayThankYou function will probably be called and executed. Otherwise, the saySorry function will probably be called and executed.
Using the Ternary Operator for Null Checks
In lots of cases, you is likely to be handling variables that will or may not have an outlined value — for instance, when retrieving results from user input, or when retrieving data from a server.
Using the ternary operator, you may check that a variable shouldn’t be null or undefined just by passing the variable name within the position of the condition operand.
This is very useful when the variable is an object. Should you attempt to access a property on an object that’s actually null or undefined, an error will occur. Checking that the item is definitely set first can aid you avoid errors.
For instance:
let book = { name: ‘Emma’, writer: ‘Jane Austen’ };
console.log(book ? book.name : ‘No book’);
book = null;
console.log(book ? book.name : ‘No book’);
In the primary a part of this code block, book is an object with two properties — name and writer. When the ternary operator is used on book, it checks that it’s not null or undefined. If it’s not — meaning it has a price — the name property is accessed and logged into the console. Otherwise, if it’s null, No book is logged into the console as a substitute.
Since book shouldn’t be null, the name of the book is logged within the console. Nonetheless, within the second part, when the identical condition is applied, the condition within the ternary operator will fail, since book is null. So, “No book” will probably be logged within the console.
Nested Conditions
Although ternary operators are used inline, multiple conditions may be used as a part of a ternary operator’s expressions. You’ll be able to nest or chain multiple condition to perform condition checks just like if…else if…else statements.
For instance, a variable’s value may rely on multiple condition. It may possibly be implemented using if…else if…else:
let rating = ’67’;
let grade;
if (rating < 50) {
grade = ‘F’;
} else if (rating < 70) {
grade = ‘D’
} else if (rating < 80) {
grade = ‘C’
} else if (rating < 90) {
grade = ‘B’
} else {
grade = ‘A’
}
console.log(grade);
On this code block, you test multiple conditions on the rating variable to find out the letter grading of the variable.
These same conditions may be performed using ternary operators as follows:
let rating = ’67’;
let grade = rating < 50 ? ‘F’
: rating < 70 ? ‘D’
: rating < 80 ? ‘C’
: rating < 90 ? ‘B’
: ‘A’;
console.log(grade);
The primary condition is evaluated, which is rating < 50. If it’s true, then the worth of grade is F. If it’s false, then the second expression is evaluated which is rating < 70.
This keeps going until either all conditions are false, which suggests the grade’s value will probably be A, or until certainly one of the conditions is evaluated to be true and its truthy value is assigned to grade.
CodePen Example
On this live example, you may test how the ternary operator works with more multiple conditions.
Should you enter a price lower than 100, the message “Too Low” will probably be shown. Should you enter a price greater than 100, the message “Too High” will probably be shown. Should you enter 100, the message “Perfect” will probably be shown.
See the Pen
Ternary Operator in JS by SitePoint (@SitePoint)
on CodePen.
Conclusion
As explained within the examples on this tutorial, the ternary operator in JavaScript has many use cases. In lots of situations, the ternary operator can increase the readability of our code by replacing lengthy if…else statements.
Related reading: