First of all, let’s take a look at the syntax of a typical if
statement:
if ( condition ) { value if true; } else { value if false; }
Now, the ternary operator:
condition ? value if true : value if false
Now, here’s what we all need to know:
- The
condition
is what you’re actually testing. The result of your condition should betrue
orfalse
or at least coerce to either boolean value. - A
?
separates our conditional from our true value. Anything between the?
and the:
is what is executed if thecondition
evaluates to true. - Finally a
:
colon. If yourcondition
evaluates to false, any code after the colon is executed.
Let’s try this with an example – Person Status
let person = { name: 'Nana', age: 30, status: null }; person.status = person.age >=16 ? 'Adult' : 'Minor';
Since 30
is greater than 16
, this evaluates to true
; and therefore, we get:
person.status = (true ? 'Adult' : 'Minor';)
Since the condition of our conditional is true
, the value between the ?
and :
is returned. In this case, that is 'Adult'
.
Enjoy!