What is the ternary operator in JavaScript?

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.

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.

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)

Copyright ©2024 Educative, Inc. All rights reserved