What is the JavaScript ternary operator?
The ternary operator is a shortcut for the if
statement. It consists of three operands; a question mark, a condition, and an expression to execute if the condition is true, followed by a colon and another expression to execute if it’s false.
let age = 26;
// condition ? expression if true : expression if false
let drink = (age >= 21) ? "Beer" : "Juice";
console.log(drink); // "Beer"
// Equivalent to:
let drink;
if ((age >= 21)) {
drink = "Beer";
} else {
drink = "Juice";
}
console.log(drink); // "Beer"
MEET THE NEW JSTIPS BOOK
You no longer need 10+ years of experience to get your dream job.
Use the 100 answers in this short book to boost your confidence and skills to ace the interviews at your favorite companies like Twitter, Google and Netflix.
GET THE BOOK NOW
MEET THE NEW JSTIPS BOOK
The book to ace the JavaScript Interview.
A short book with 100 answers designed to boost your knowledge and help you ace the technical interview within a few days.
GET THE BOOK NOW