Ternary operator in Javascript

Learn about how and when to use ternary operator in Javascript


Ternary operator in Javascript

Ternary operator is also denoted as conditional operator.

Ternary operator is the compact version of if statement.

If you’re going to check for simple condition, then ternary operator is highly recommended instead of if block.

Example of using normal if condition

function printName(name, inUpperCase) {

if(inUpperCase) {
      name = name.toUpperCase();
    } else {
      name = name.toLowerCase();
    }

console.log(name);

}

The above code can be simplified into

function printName(name, inUpper) {
    name=(inUpper===true) ? name.toUpperCase() : name.toLowerCase();

console.log(name);
  }

There are three parts in ternary operator


Condition part β†’ Condition to check

true part β†’ executed if the condition is true

false part β†’ executed if the condition is evaluated to false

Do follow me Javascript JeepπŸš™πŸ’¨Β .

Please make a donation here. 80% of your donation is donated to someone needs food πŸ₯˜. Thanks in advance.

Leave a comment

Design a site like this with WordPress.com
Get started