Tutorials Tonight
Follow Us

Ternary Operator Javascript - Write Cleaner Code


In this tutorial, you will know about the ternary operator, how to use it and how to write cleaner code using it.

Ternary operator in javascript

The ternary operator is a very useful operator in javascript. It is used to check a condition and execute a statement based on that condition. It is used to check if a value is true or false and execute a statement based on that.

The ternary operator is the only javascript operator which takes 3 operands for the operations. It evaluates a condition and executes a block of code based on it.

Here is an example of the ternary operator in javascript.

Example

var user = {
  name: 'John',
  isLoggedIn: false,
  role: 'user'
};
// Ternary operator to check isAdmin
var isAdmin = (user.role === 'admin') ? true : false;

console.log(isAdmin);

The ternary operator is just like if...else statement and can be used to replace it to write cleaner code in many cases.

Syntax of the ternary operator

The syntax of the ternary operator is as follows:

condition ? expression1 : expression2

From the syntax above you can see that the ternary operator contains 1 condition and 2 expressions.

Here is how it works:

Ternary operator example

Let's see how the ternary operator works in practice.

Example

// condition ? expression1 : expression2
true ? alert("Condition is true") : alert("condition is false");

// evaluating condition => (10 > 5) returns true
10 > 5 ? console.log("Yes 10 > 0") : console.log("No!");
▶ Try It

Compare ternary operator with if...else

The ternary operator is similar to the if...else statement. The main difference is that the ternary operator is more readable and easier to understand.

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 the mark is greater than 40 then pass else fail.

Compare both conditional operators if...else and ternary.

Example

let mark = 50;
// using if else
if (mark >= 40) {
  console.log("Pass!");
}
else {
  console.log("Fail!");
}

console.log("-------------------")

// using ternary
mark >= 40 ? console.log("Pass!") : console.log("Fail!");
▶ Try It

You can see that the ternary operator is much easier to read and understand than if...else.


Assigning a value using ternary operator

The ternary operator can be used to assign a value to a variable. It is very useful when you want to assign a value to a variable based on a condition.

Using if...else also you can set a value to some variable but that looks like a lot of code and it is not easy to read. Using the ternary operator you can write clean code.

Let's see an example of how to use the ternary operator to assign a value to a variable.

Example

const isLeapYear = true;
const numberOfDays = isLeapYear ? 366 : 365;
console.log(numberOfDays);
▶ Try It

Ternary operator multiple conditions

Ternary operator can be used to check multiple conditions and assign a value to a variable based on that.

Let's see an example of how to take multiple conditions with a ternary operator.

Example

const num = 15;
// is divisible by 3 and 5
const isDivisibleBy3And5 = (num % 3 === 0 && num % 5 === 0) ? true : false;
console.log(isDivisibleBy3And5);

Here is another example of multiple conditions with the ternary operator.

Example

let age = 22;
// find age group
let group = age < 18 ? "underage" : age < 65 ? "adult" : "elder";
console.log(group);

If you do not understand how it resulted in "adult" then here is a little more explanation.

The ternary operator is a combination of multiple conditions. The condition given (age < 18) is false in the above code so it jumped to the next condition (age < 65) and return true.

Look at the code below it is the ternary operator in multiple lines.

Same as above code

let age = 22;
// find age group
let group = age < 18 ? "underage" // if
            : age < 65 ? "adult"  // else if
            : "elder";            // else
console.log(group);

Nested Ternary Operator javascript

Ternary operators can also be nested to check multiple conditions same as if...else but it becomes more complicated to read and also is not recommended.

First, see code to find leap year using if...else statements.

Example

const year = new Date().getFullYear();
let isLeapYear;
if (year % 4 === 0) {
  if (year % 100 === 0) {
    if (year % 400===0) {
      isLeapYear = "a leap year";
    }
    else {
      isLeapYear = "not a leap year";
    }
  }
  else {
    isLeapYear = "a leap year";
  }
}
else {
  isLeapYear = "not a leap year";
}
console.log(year + " is " + isLeapYear);

Now let's see how to use the ternary operator to check if a year is a leap year.

Example

const year = new Date().getFullYear();
const isLeapYear = year % 4 === 0 ? (year % 100 === 0 ? (year % 400 === 0 ? "a leap year" : "not a leap year") : "a leap year") : "not a leap year";
console.log(year + " is " + isLeapYear);
▶ Try It

Ternary operator in loops

Ternary operators can also be used in loops. It is very useful when you want to check a condition in a loop.

Let's see an example of how to use ternary operator in a loop.

Example

const numbers = [1, 2, 3, 4, 5];
const result = numbers.map(number => number > 3 ? "bigger than 3" : "smaller than 3");
console.log(result);

Ternary operator in loops with multiple conditions

Ternary operators make code very clean when you have to work multiple conditions inside look.

See the example to understand.

Example

const numbers = [1, 2, 3, 4, 5];
const result = numbers.map(number => number > 3 ? "bigger than 3" : (number < 3 ? "smaller than 3" : "equal to 3"));
console.log(result);

Frequently ask questions

  1. How do you use multiple conditions in a ternary operator?

    You can separate multiple conditions with logical operators like && or || and use the ternary operator as it is.

  2. Can ternary operator have multiple statements?

    Yes, you can have multiple statements inside the ternary operator.
    For example: a ? b : c ? d : e.

  3. Can ternary operator have multiple lines?

    Yes, you can have multiple lines inside the ternary operator.
    For example:

    a ? b 
      : c ? d 
      : e