Tutorials Tonight's Logo
Follow Us

JAVASCRIPT TERNARY OPERATOR


What is a ternary operator in javascript?

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

A ternary operator in javascript is used to replace if...else statement in certain situation.

It accepts 3 operand and 2 operators. Here is syntax of ternary operator.

condition ? expression1 : expression2

From syntax above you can see that ternary operator contains 1 condition and 2 expressions. If condition evaluated is true then expression1 is executed else expression2 is executed.

javascript ternary operator example

// condition ? expression1 : expression2
true ? alert("Condition is true") : alert("condition is false");
// evaluating condition
10 > 5 ? console.log("Yes") : console.log("No");
▶ Try It

If...else VS ternary operator

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

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

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

Assigning a value using ternary operator

While using if...else you can set a value to some variable on some condition. You can do same using ternary operator and writing less code.

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

Nested Ternary Operator

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

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

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 the same code using ternary operators.

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

More Learning

Want to learn more about programming and web development? We have a few recommendations for you.


Follow Us

Copyright © Tutorials Tonight. All Rights Are Reserved.