? : , also known as the conditional operator.
So let's explore the ternary operator.
What is it?
So as the name implies the ternary operator
? :takes three operands - one before the operand, one between it and one after it.
So the meaning out of the way let's explore how the ternary operator works.
How it works?
See this syntax for better understanding
- expression1 is the expression to be evaluated and returned when the condition is true.
- expression2 is the expression to be evaluated and returned when the condition is false.
Let's even see this in action.
var id = 1; var item = (id == 1) ? "Football" : "Tennis Racket"; console.log(item); // Football
idis equal to 1 i.e the condition is met, therefore the second operand -
var id = 2; var item = (id == 1) ? "Football" : "Tennis Racket"; console.log(item); // Tennis Racket
idis not equal to 1 i.e the condition is not met, therefore the third operand -
Tennis Racketis returned.
When to use it?
The ternary operator is handy:
- When you have only two things to do after a certain condition is checked - one when the condition is true and one when the condition is false. This is different from the if statements where you can nest more
if's and even add
else if's just because you have a whole lot of conditions to test.
- When there are not complex multiple statements to be executed after condition evaluation. The ternary operator is given to add simplicity to conditional programming and therefore isn't meant to handle complex statements in the second and third operands.
Well generally speaking you could use the
iffamily of statements and even the
switchstatement to condition-check code instead of the ternary operator, but to some it seems unreasonably long.
Take your time to understand or review any thing you didn't understand in this unit or have forgotten respectively because the next unit will be accelerating the ideas and concepts laid out by this unit.