JAVASCRIPT TERNARY OPERATOR
What is a ternary operator in javascript?
The ternary operator
is only javascript operator which takes 3 operands, it evaluates a condition and executes a block of code based on it.
A ternary operator in javascript is used to replace if...else statement in certain situation.
It accepts 3 operand and 2 operators. Here is syntax of ternary operator.
condition ? expression1 : expression2
From syntax above you can see that ternary operator contains 1 condition and 2 expressions. If condition evaluated is true
then expression1 is executed else expression2 is executed.
javascript ternary operator example
Example
If...else VS ternary operator
Let's see an example and understand how convenient and easy it is to use the ternary operator. Using a ternary operator you can write clean code.
In the example below check if a student passed the exam if mark is greater than 40 than pass else fail.
Compare both conditional operators if...else and ternary.
Example
Assigning a value using ternary operator
While using if...else you can set a value to some variable on some condition. You can do same using ternary operator and writing less code.
Example
Nested Ternary Operator
Ternary operators can be nested to check multiple condition same as if...else but it becomes more complicated to read and also is not recomended.
First see code to find leap year using if...else statements.
Example
Now let's see the same code using ternary operators.
Example