Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ternary
javascript
operator

What is the ternary operator in JavaScript?

Educative Answers Team

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The conditional ternary operator assigns a value to a variable based on some condition. It is used in place of the if statement.

The ternary operator is the only JavaScript operator that takes 3 operators.

Syntax

svg viewer
  • The condition is the expression whose value determines which value is used.
  • The value after the ? is returned if the condition returns true.
  • The value after the : is returned if the condition returns false.

Example

The code below uses the ternary operator to show a simple If else condition testing code, and its equivalent code.

var grade;
var marks = 43;
if (marks < 30) {
grade = 'Fail';
}
else {
grade = 'Pass';
}
console.log(grade)

Multiple Ternary operators

If we want to check multiple variations of the same test case, we can use multiple else if statements. The code below shows how these multiple variants can be implemented through both else if and ternary operators.

var grade;
var marks = 68;
if (marks < 30) {
grade = 'Fail';
}
else if (marks < 60) {
grade = 'Pass'
}
else if (marks < 90) {
grade = 'Distinction'
}
else {
grade = 'High Distinction';
}
console.log(grade)

Multiple Operations

We can also perform more than one operation for a ternary operator, but the commands must be separated with commas. First, the code below sets the value of the grade variable. Then, if the corresponding condition is fulfilled, it prints a message with that variable.

var marks = 43
var grade;
(marks < 30) ? (grade ='Fail', console.log("Better luck next time "))
: (grade ='Pass', console.log("Congratulations "));
console.log(grade)

RELATED TAGS

ternary
javascript
operator
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring