JavaScript Ternary Operator – How it works
What is Ternary Operator?
The word “Ternary” has derived from the Late Latin word ternarius (consisting of the three things), from terni (“three each”). It is the only operator in JavaScript that consists of three parts.
A ternary Operator or Conditional Operator is a kind of operator which works as an alternative to the if-else condition and is written in a single line. It is also known as shorthand if-else or inline if statement.
The Ternary Operator accepts three operands
- User-defined condition followed by the question mark “?“.
- True Expression -> If the condition specified is true then this part of the code will get executed followed by “:”
- False Expression -> Else if the given condition is false then this part of the code gets executed
Syntax
Condition ? TrueExp : FalseExp
Let’s look into the Parameters of the Ternary operator
- Condition: Firstly, we need to write our expression that will be checked whether the given statement is true or false
- TrueExp: If the given statement or condition is true then the TrueExp part will get executed and returns the result.
- FalseExp: If it is false then the FalseExp part will get executed and returns the result.
⌚ for Hands-On
A Basic Example
let age = prompt(“Enter your age: “);
const votingAge = age >= 18 ? “Can Vote” : “Cannot Vote”;
console.log(You ${votingAge} in the elections);
Code language: JavaScript (javascript)
Output
Enter your age: 19
You can vote in the elections
// since the entered age is more than the condition i.e. 18, hence it renders the True value i.e “Can Vote”
Fun with NULL Values
What if someone gives a null value to the expression ?. Let’s check
const greet = (human) => {
const name = human ? human.name : “Buddy”;
return `Hola ${name}`;
}
console.log(greet({name : “Aman”}));
console.log(greet(null));
Code language: JavaScript (javascript)
Output
Hola Aman //since the value is provided hence it accepts the trueExp value and prints the value passed
Hola Buddy //since the null value is provided hence it accepts the value in falseExp
Nested Ternary Operator
Let’s look into the nested one as well. It is similar to the nested if-else condition i.e. if … else if … else
let num = prompt(“Enter any Integer: “);
let res = (num >= 0) ? (num == 0 ? “Zero” : “Positive”) : “Negative”;
console.log(res);
Code language: JavaScript (javascript)
Output
Enter any Integer: 28
Positive
// here we are checking whether the given value of the integer is positive, negative, or equivalent to 0.
If the num value is greater than or equal to 0, then it will come to the true part and will check again whether the value is equal to 0 or greater than 0. If equals then return 0 else Positive or if smaller than zero then return the false part i.e. Negative
NOTE:- It is always recommended to avoid the nested ternary operator as it doesn’t look very clean which sometimes makes it hard to read.
Conclusion
In summary, Ternary Operator or Shorthand if-else operator or Inline if statement in JavaScript is a very common way to express the if-else condition in a single line yet very powerful that one must use it with some precautions.
Ternary Operator can make your code (if-else condition) very concise if used efficiently else it can lead to difficulty in maintaining, reading, and understanding the code. Hence it is always advised to maintain extra caution while using ternaries as its goal should not be only saving 2 to 3 lines of code else it should make the code simple and readable.
Sharing is caring
Did you like what Vishnupriya wrote? Thank them for their work by sharing it on social media.
No comments so far
Curious about this topic? Continue your journey with these coding courses: