How to use Ternary Operator in JavaScript?

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,

  1. Condition: In the first operand we add a condition that has to be either true or false.
  2. True: if condition matches or gets success then ternary operator runs second operand.
  3. False: if condition fails to match or fails then ternary operator runs third operand.

Conclusion

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.


Written by
I am a skilled full-stack developer with extensive experience in creating and deploying large and small-scale applications. My expertise spans front-end and back-end technologies, along with database management and server-side programming.

Share on:

Related Posts