Ternary operator in JavaScript

Ternary operator in JavaScript

This tutorial will teach you how to use the ternary operator to make your code more concise.

The ternary operator is also known as the conditional operator. It is the only operator in JavaScript that operates on three operands. It is a cleaner alternative to the if-else statement. The working of the ternary operator is the same as the if-else statement.

The syntax of the ternary operator looks like this :

conditional ? exprIfTrue : exprIfFalse

In the above syntax

  • conditional is the expression that evaluates to return a boolean value.
  • exprIfTrue denotes the expression/ block of code that must be executed when the conditional returns true
  • exprIfFalse denotes the expression/ block of code that must be executed when the conditional returns false

To understand the working of the ternary operator, let us compare it with the if/else statement.

Let's say, you have to write a simple program to check if a person is eligible to vote. To keep it simple, the only criteria for eligibility is the person's age should be above 18.

let age = 20;
if(age < 18){
    console.log("Not eligible to vote") //exprIfTrue
}else{
    console.log("Eligible to vote") //expxrIfFalse
}

// output: Eligible to vote

Here, the conditional is written in the braces after if statement i.e age < 18 Now let us have a look at how the same program can be written using the ternary operator.

let age = 20
age < 18 ? console.log("Not eligible to vote") : console.log("Eligible to vote")

And there you go, The same program with ternary operator looks way more concise compared to if/else.

Thank you for reading this tutorial. Do leave your feedback in the comments below