Even if you're fairly new to the world of Javascript, you've probably written a simple IF/ELSE statement AT LEAST once. While there is nothing wrong with simple IF/ELSE statements, there is a cooler / "cleaner" way to write them in JS that you may not have experienced or used yet.
🥁🥁 enter Conditional (ternary) operator 🥁🥁
The conditional (ternary) operator allows us to turn this:
let age = 19
if (age >= 18){
console.log("You are an adult")
} else {
console.log("You are not an adult")
}
// returns "You are an adult"
...into this:
let age = 19
age >= 18 ? console.log("You are an adult") : console.log("You are not an adult")
// how it works:
// condition ? return this if condition is true : return this if condition is false
// again, returns "You are an adult"
According to MDN the ternary is right associative, meaning that it can be "chained", similar to an if, else if, else if, else chain. Meaning we COULD do something like this:
function getGrade(grade){
return (grade >= 90) ? "A"
: (grade < 90 && grade >= 80) ? "B"
: (grade < 80 && grade >= 70) ? "C"
: (grade < 70 && grade >= 60) ? "D"
: "F"
}
getGrade(100) // "A"
getGrade(85) // "B"
getGrade(55) // "F"
// which would be equivalent to...
function getGrade(grade){
if (grade >= 90){
return "A"
}
else if (grade < 90 && grade >= 80) {
return "B"
}
else if (grade < 80 && grade >= 70) {
return "C"
}
else if (grade < 70 && grade >= 60) {
return "D"
}
else {
return "F"
}
}
getGrade(100) // "A"
getGrade(85) // "B"
getGrade(55) // "F"
With clean formatting, nesting or chaining the ternary operator could be a perfectly fine way to write your code in a sleeker / cleaner way, but many could argue and say that the fully written out if / else if / else statement makes your code easier to read, especially in more complicated situations — which is equally, if not more, important than writing sleek code.
Remember...
As always, refer to MDN for more info:
Conditional (ternary) operator: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator
Feel free to reach out on any of my socials for questions, feedback (good and bad), or just to connect / say hello 👋.
Top comments (0)