Last updated on December 28, 2022
Almost all languages have different ways to achieve the same output. For example in JavaScript, the conditional statement in ternary operator returns the same result. Ternary operator helps to shorten the conditional statement and the code looks clean and easy to understand.
You can use a shortened instead of the if-statement block. For example, in my style, the if-statement or conditional statement takes 5 lines to do the task that can be done in just one line through a ternary operator.
if(condition) {
...do something;
}else{
...do something
}
The ternary operator directly assigns the end result to the variable that needed to be assigned.
let variable = condition ? expressionIfTrue : expressionIfFalse;
Let’s divide ternary operator into the three operands,
A shortened version of the condition statement is called the ternary operator. Ternary operators can be simple or nested. Using the short version the expression must be in the same type. In a shortened version of the condition first is a conditional argument then a true expression (:) then a false expression. The ternary operator makes the code concise.