Came across it when traversing the sea of JS. I don't know why, but it looks so elegant. And I like it so much I've decided to write about it.
tl:dr version: Basically it's a substitute for the "if" statement.
The premise
The passage bellow is a straight copy from the MDN website.
The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark (?), then an expression to execute if the condition is truthy followed by a colon (:), and finally the expression to execute if the condition is falsy. This operator is frequently used as a shortcut for the if statement.
This means, you can write an entire "if" statement using just ":" and "?".
Example
Let's say we're asking a user to input his name with prompt, and then we would like to print out his name with a "greeting". If the user doesn't input anything, we will assign a default value.
if statement
const userName = prompt("Gief me your name!!");
const userGreeting = " waddles around like recieving a prostate exam";
if (userName === "") {
const userNameDefault = "Yo'momma";
console.log(userNameDefault + userGreeting);
} else {
console.log(userName + userGreeting);
}
ternary operator
const userName = prompt("Gief me your name!!");
const userGreeting = " waddles around like recieving a prostate exam";
userName === ""
? (userName = "Yo'daddy") + console.log(userName + userGreeting)
: console.log(userName + userGreeting);
ternary operator with template literal
const userName = prompt("Gief me your name!!");
const userGreeting = `${userName} waddles around like recieving a prostate exam`;
userName === ""
? (userName = "Yo'daddy") + console.log(userGreeting)
: console.log(userGreeting);
What the MDN files don't mention if you have more expressions to execute. You can simply chain them together with '+'.
Conclusion
As you see, the code is shorter and looks a little easier to read once you've got used to it.
Top comments (0)