JavaScript Ternary (Conditional) Operator Complete Tutorial

In this section, we will learn what the ternary operator is and how to use it in JavaScript.

What is Ternary Operator in JavaScript? (JavaScript Conditional Operator)

The ternary operator is the short version of using the `if else` statements.

Basically via the ternary operator, we can define one condition and two values. If the result of the condition is true, the first value will return, otherwise the second one will return instead.

JavaScript Ternary Operator Syntax:

This is the structure of the ternary operator:

condition ? expression_True : expression_False;

`condition`: the condition is the one that we declare to either return true or false result.

`expression_true`: This is the first value we set for the ternary operator and it will be returned if the result of the condition is true.

`expression_false`: This is the second value of the ternary operator and of course it will be returned only if the result of the condition becomes false.

`?`: between the condition and the first value we use question mark `?` to separate them from each other.

`:`: also between the first and second value, we use colon `:` to separate these two values from each other.

Example: using ternary operator in JavaScript

const emp = "Manager";
const salary = emp == "Manager"? 10000:8000;
console.log(`The salary is: ${salary}`);

Output:

The salary is 10000

In this example, the value of the `salary` variable is dependent on the value of the `emp` variable.

If the value of the `emp` is `Manager` then the value 10000 will be stored in the `salary` variable. But if the value of the `emp` wasn’t `Manager` then the value 8000 is the one to be stored in the `salary` variable.

If we wanted to write the program above via the `if else` statements, it would be like this:

const emp = "Manager";
let salary;
if (emp == "Manager"){
  salary = 10000;
}else{
  salary = 8000;
}
console.log(`The salary is: ${salary}`);

Output:

The salary is: 10000

Nested Ternary Operator in JavaScript

We can use any expression that results in a value as the operands in the condition, or as the return values of a ternary operator.

This includes the use of other ternary operators as well! Because after all, the result of a ternary operator is another value!

This is known as nested ternary operator.

Example: creating nested ternary operator in JavaScript

const name1 = "John";
const name2 = "Omid";
const name3 = "Ian";
const name4 = "Elon"; 
const result = (name1>name2?name1:name2)>(name3>name4?name3:name4)?"Yes":"No"; 
console.log(result);

Output:

Yes

Note: the purpose of this example is just to show you how we can use a ternary operator inside another ternary operator.

Leave a Reply