Ternary operator '?'
Ternary operator '?'
Sometimes we need to assign a variable depending on a condition.The so-called "ternary" or "question mark" operator lets us do that shorter and simpler.
Syntax
Let result = condition ? value1 : value2
Multiple '?'
Let age = prompt('age?', 18);
let message = (age < 3) ? 'Hi, baby!' :
(age < 18) ? 'Hello!' :
(age < 100) ? 'Greetings!' :
'What an unusual age!';
alert( message );
A sequence of question mark ? operators allows returning a value that depends on more than one condition.
Non-traditional use of '?'
Related concepts
→
Ternary operator '?'
→