Ternary operator in JavaScript

Savannah Hayes
3 min readMar 31, 2022

--

In mathematics, a ternary operation basically takes any three elements and combines them to form a single element.

In computer science, a ternary operator is an operator that takes three arguments. The ternary operator is the only JavaScript operator that takes in three operands: a condition, question mark, and a colon. This operator works similar to an if statement.

condition — The first operator is the conditional expression.

? — The second operator, will run if the condition is true.

: — The third operator, will run if the condition is false.

The ternary operator can be written in one line, instead of in multiple lines with the if, if else, and else if statements for example. The syntax looks something to this below.

In JavaScript, a ternary operator expects three operands, it always requires a condition, and two expressions to execute, so you can’t leave it blank or leave the colon out. If you don’t have an else statement, you can use null to the right of the colon operator. This is the same as using an if statement for example.

Example of a ternary operator in action compared to an if else statement:

We declare a function called testResults which takes in a percentage grade as a parameter. The function then returns the result of the ternary operator if the grade passed in is greater than 60% we return the string “Passing” else we return the string “Failing”.

Did you know we can chain conditionals?…

using the ternary operator just like when we use else if statements to check for multiple conditions. We can do the same with a ternary operator, by chaining conditionals we can add additional conditions after the colon of the previous false condition.

We declare a function called testResults which accepts one parameter. Inside the body of the function, we return the output of a ternary operator which chains on conditions. If the grade parameter is greater than 90%, the string “Letter grade A” will be returned. Else if the grade parameter is greater than 80% but less than 90%, the string “Letter grade B” will be returned, and so on for the rest of the conditions…

If none of these conditions are true, so if grade is not between 100–60 percent, the string “Not a passing grade” will be returned. In the examples on the bottom we invoke the testResults function passing in 73% as the argument. This is greater than 70% so it returns the string “Letter grade C”. And in the last couple of lines we invoke the testResults function passing in 30% as the argument which returns the string “Not a passing grade” as it doesn’t meet all the previous conditions.

--

--