Ternary operator in JavaScript

In this tutorial, we will understand how to use the ternary operator in JavaScipt and its use. We will also learn how it is different and similar to if else conditional statement.

Generally, we use if-else statement to execute a code based on condition.

For example,

Create a file check1.js

var a=9;
 document.write("greater than 3");
 document.write("not greater than 3");


greater than 3

In the above example, we can know the given number is greater than 3 or not using if else statement.

The same can be done using Ternary conditional operator in JavaScript.

What is a Ternary operator in JavaScript

It is a conditional operator in JavaScript. It is given the name as ternary operator because this operator has 3 operands.

Syntax of Ternary operator:

(condition) ? (statement to be executed if condition is true) : (statement to be executed if condition is fasle)

Let us see some examples of how this ternary operator can be used instead of if else statement so that it makes the code more concise.

Example 1:

Consider the above example i.e.,

To check a number is greater than 3 or not.

Create a file check2.js

 var a=7;
(a>3) ? document.write("greater than 3") : document.write("not greater than 3");


greater than 3


  • Need of ternary operator (?:)

Here it checks the condition , if it is true statement 1 will be executed else, statement 2 will be executed same as if-else but using ternary operator it takes only a single line of code.

Example 2:

we can do the same in different way using ternary operator.

var a=7;
var res;
res=(a>3) ? "greater than 3" : "not greater than 3";


greater than 3


Here the value is assigned to a variable based on the condition and later we can display the result.

Points to Remember:

  • If we have multiple conditions we can use nested ternary operator but it is hard to understand the code later. So, it is recommended to use if/ese or switch statements.


var a=72;
var res;
res=(a>=100 && a<1000) ? "3-digit number" : (a>=10 && a<100) ? "2-digit number" : "not a 3-digit or 2-digit number";


2-digit number

Leave a Reply

Your email address will not be published. Required fields are marked *