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
The condition is evaluated, if it's truthy then value1 is returned, otherwise - 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 '?'

It is not recommended to use the question mark operator in this way.

Let company = prompt('Which company created JavaScript?', '');

*!*
(company == 'Netscape') ?
   alert('Right!') : alert('Wrong.');
*/!*

Sometimes the question mark ? is used as a replacement for if.

Ternary operator '?' — Structure map

Clickable & Draggable!

Ternary operator '?' — Related pages: