Ternary operator in Javascript
If the operator is applied on three operands then it is called Ternary operator. This is also known as conditional operator as a condition is followed by ? and true-expression which is followed by a : and false expression. This is oftenly used as a shortcut to replace if-else statement
Syntax
condition ? true-expression : False-expression
Example
let x = 2, y= 3;
let z = x > y ? x : y; // z will be assigned with x if x > y and with y if x < y
console.log(z); // prints 3
If we need to write the same logic using If-else, the code looks bigger with more statements. Hence ternary operator is used as a shortcut for these kind of scenarios.
let x = 2, y= 3;
let z;
if ( x > y) {
z = x;
} else {
z = y;
};
console.log(z); // prints 3
Another common scenario where we often use ternary operator is when you want to handle values which can be possibly be null sometimes.
function greetings(student) {
var n = student ? student.name : "NA";
return "Hello " + n;
}
console.log(greetings({name: 'foo'})); // prints Hello foo
console.log(greetings(null)); // prints Hello NA
You can try yourself here