Ternary Operator and it's superpowers
Use cases where we can use the ternary operator to make things easier and quicker.

Hey π My name is Debasish, I'm a System Engineer and a passionate Web Developer who loves to experiment with new technologies and build projects. I like to share and showcase my tips and knowledge on this blog. Since you are here feel free to browse through some of my posts, I'm sure you will find something useful and interesting. Hope you are feeling excited!
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




