Yes it's a Confusing Operator πŸ€”

Suhail Roushan πŸš€
3 min readApr 24, 2022

(Ternary Operator )

A ternary operator can be used to replace an if..else statement in certain situations. Before you learn about ternary operators, be sure to check the JavaScript if...else tutorial.

What is a Ternary operator?

A ternary operator evaluates a condition and executes a block of code based on the condition.

Its syntax is:

condition ? expression1 : expression2

The ternary operator evaluates the test condition.

  • If the condition is true, expression1 is executed.
  • If the condition is false, expression2 is executed.

The ternary operator takes three operands, hence, the name ternary operator. It is also known as a conditional operator.

Let’s write a program to determine if a student passed or failed in the exam based on marks obtained.

Example: JavaScript Ternary Operator

// program to check pass or faillet marks = prompt('Enter your marks :');// check the condition
let result = (marks >= 40) ? 'pass' : 'fail';
console.log(`You ${result} the exam.`);

Output 1

Enter your marks: 78
You pass the exam.

Suppose the user enters 78. Then the condition marks >= 40 is checked which evaluates to true. So the first expression pass is assigned to the result variable.

Output 2

Enter your marks: 35
You fail the exam.

Suppose the use enters 35. Then the condition marks >= 40 evaluates to false. So the second expression fail is assigned to the result variable.

Ternary Operator Used Instead of if…else

In JavaScript, a ternary operator can be used to replace certain types of if..else statements. For example,

You can replace this code

let completedLessons = 20;
let result;
if (completedLessons >= 15) {
result = "You are eligible to apply for a driving license.";
} else {
result = "You need more lessons to be eligible for a driving license.";
}
console.log(result);

with

// ternary operator to check the eligibility to vote
let creditHours = 12;
let result =
(creditHours >= 9) ? "You are eligible " : "You need more credit hours to qualify for the student discount.";
console.log(result);

The output of both programs will be the same.

Output

You are eligible

Nested ternary operators

You can also nest one ternary operator as an expression inside another ternary operator. For example,

// program to check if number is positive, negative or zero
let a = 3;
let result = (a >= 0) ? (a == 0 ? "zero" : "positive") : "negative";
console.log(`The number is ${result}.`);

Output

The number is positive.

Note: You should try to avoid nested ternary operators whenever possible as they make your code hard to read.

--

--

Suhail Roushan πŸš€

⭐ Software Engineer at T-Works πŸ§‘β€πŸ’» Full Stack Web Developer πŸŽ“ CS.CODE.IN Fellow '21 πŸ’‘ Startup Tech Innovator πŸ‘¨β€πŸŽ¨ UI/UX Designer πŸ€– Automation