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.
?
is returned if the condition returns true
.:
is returned if the condition returns false
.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)
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)
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 = 43var grade;(marks < 30) ? (grade ='Fail', console.log("Better luck next time ")): (grade ='Pass', console.log("Congratulations "));console.log(grade)