JavaScript Ternary Operator
JavaScript offers various ways to write conditional statements, it can be used to replace an if…else statement in certain situations. In this article, we will look into the ternary operator in JavaScript, exploring its syntax and examples. By the end, you will learn about how and when to use the conditional/ ternary operator effectively in your code.
What is a Ternary operator?
A ternary operator evaluates a condition and executes a block of code based on the condition.
Syntax
condition ? <expression if true> : <expression if false>
Parameters
condition: An expression whose value is used as a condition.
<expression if true>: An expression that is executed if the condition
evaluates to a truthy value (one which equals or can be converted to true
).
<expression if false>: An expression which is executed if the condition
is falsy (that is, has a value which can be converted to false
).
The condition is evaluated, and its result determines which expression is executed next. If the condition evaluates to true, expression1 is executed; otherwise, expression2 is executed. The evaluated expression’s value is returned as the result of the ternary operation.
Examples
const isStudent = true;
const output = isStudent ? "Welcome back!" : "Please log in.";
console.log(output); //"Welcome back!"
Here, the ternary operator checks the boolean value of isStudent. If it is true, the string "Welcome back!" is assigned to output; otherwise, "Please log in." is assigned and printed to the console. The code above will print “Welcome back!” because isStudent is true.
Here’s another example:
function check() {
let age = 13
let result = (age >= 13) ? "You a Teenager" : "You are not a Teenager";
console.log(result);
}
check(); // You a Teenager
Handling null values
One common usage is to handle a value that may be null
:
const greeting = (person) => {
const name = person ? person.name : "stranger";
return `Howdy, ${name}`;
};
console.log(greeting({ name: "Alice" })); // "Howdy, Alice"
console.log(greeting(null)); // "Howdy, stranger"
— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —
Ternary Operator Used Instead of if…else
In JavaScript, a ternary operator can be used to replace certain types of if…else statements. For example,
// program to check pass or fail using if...else
let marks = prompt('Enter your marks :');
//Check the condition
if (marks >= 40) {
result = 'pass';
} else {
result = 'fail';
}
console.log(`You ${result} the exam.`);
// program to check pass or fail using ternary operator
let marks = prompt('Enter your marks :');
//Check the condition
let result = (marks >= 40) ? 'pass' : 'fail';
console.log(`You ${result} the exam.`);
Both programs will print out the same result.
Case selectors
When properly formatted, the conditional operator can be used to write simple and coherent case selectors. For example:
const letter = 'H';
vehicle = (letter == 'B') ? bus :
(letter == 'A') ? airplane :
(letter == 'T') ? train :
(letter == 'C') ? car :
(letter == 'H') ? horse :
feet;
Conditional Chains
The ternary operator is right-associative, which means it can be “chained” in the following way, similar to an if … else if … else if … else
chain:
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;
}
}
Resources
Conclusion
The ternary operator provides a concise and elegant way to write conditional statements in JavaScript. With practice, you can leverage this operator to write more expressive and efficient JavaScript code.
If you would like to connect with me personally, do send me a DM on Twitter, and I would love to hear from you.