Ternary Operator and it's superpowers
Use cases where we can use the ternary operator to make things easier and quicker.
If you have been using if else statements frequently in your code for checking any condition then you will be finding the ternary operator handy, it is a very good alternative of if...else
statement.
The ternary operator in JavaScript takes 3 operands, first a condition that is followed by a (?)
question mark and then an expression to execute if the condition is true
followed by a (:)
colon and then the expression to execute if the condition is false
.
Syntax:
condition ? expressionToExecuteIfTrue : expressionToExecuteIfFalse
Simple Example:
const age = 20;
const drivingLicence = age >= 18 ? "Has Driving Licence" : "Don't have driving Licence";
console.log(drivingLicence ); // "Has Driving Licence"
Comparison with if..else
//if else
if (guess > secretNumber){
if(score > 1){
document.querySelector('.message').textContent = '๐ Too High'
}else{
document.querySelector('.message').textContent = '๐ You lost'
}
}else if (guess < secretNumber){
if(score > 1){
document.querySelector('.message').textContent = '๐ Too Low'
}else{
document.querySelector('.message').textContent = '๐ You lost'
}
}
//Above code refactored with ternary operator and from two blocks of if else to only one block
if(guess !== secretNumber){
if(score > 1){
//using ternary operator here
document.querySelector('.message').textContent = guess>secretNumber ? '๐ Too High' : '๐ Too Low'
}else{
document.querySelector('.message').textContent = '๐ You lost'
}
}
You can also use One Ternary Operator Inside Another :
let number = 20;
let marks = number >= 90 ? "A+"
: number >= 80 ? "A"
: number >= 70 ? "B+"
: number >= 60 ? "B"
: number >= 50 ? "C+"
: number >= 40 ? "C"
: "F";
console.log(`Here is your marks grade ${marks}`);
In this way, you can write cleaner code than using the if-else
statement
If you have any issues or questions about it, feel free to contact me. Thank you ๐ for reading! like, share and subscribe to my newsletter for more!
๐Debasish Lenka