GoConqr has a new look! Let us know what you think.

Module 15 of 18 · Media

The ternary operator

Kostas Diakogiannis

The ternary operator

The ternary operator

The ternary operator is used exactly the way an if ... else statement is used with the exception that no multiple if conditions are allowed.  There is only one condition that is being checked and this evaluates to either true or false. 

Based on the outcome we execute a different part of code. 

It an error prone syntax and beginners need to be careful with it, but when used correctly is very concise, easy to read and save work from syntax mess.

The syntax is: 

condition ? code to be executed in case of true : code to be executed in case of false

ex. 10 > 5 ? console.log('yes it is bigger') : console.log('nope it is not') // prints 'Yes it is bigger'

ex. 10 < 5 ? console.log('yes it is bigger') : console.log('nope it is not') // prints 'nope it is not'

Mostly it is used instead of single if...else statements when there is only one condition to be checked.

Instructions

You must submit an attempt for this quiz to progress. You can submit it after the last question.

Go to the chosen module

Feedback

What is it about?

What do you think of the new look?

How do you like it?