Aisha Wahab O.
1 min readMar 8, 2024

The ternary operator is a concise way of expressing conditional statements in a single line of Javascript code. You can think of it as a shorthand for an if/else statement. It takes three operands, or inputs, and returns a value based on the result of a logical condition. So, instead of using if/else statements with lots of conditions, the ternary operator allows for more concise and readable code.

Let’s look at the below examples to see how the ternary operator works.

When we have a number and we have to find out if it’s even or odd and the result has to be stored in a variable , then we print later.

Examples:

let num = 11
let result

if(num%2===0)
result = "Even"

else
result = "Odd"

console.log(result);

//Odd

let num = 8
let result

if(num%2===0)
result = "Even"

else
result = "Odd"

console.log(result);

//Even

However , instead of using the above we can use a special function called the ternary operator.

let num = 8
let result

result = num%2===0 ? "Even" : "Odd"


console.log(result);

//Even

If the condition is true , output’d = Even.

And if the condition is false, output= Odd.

In essence, the ternary operator is a concise way of phrasing conditional statements.

Aisha Wahab O.
Aisha Wahab O.

Written by Aisha Wahab O.

I currently write on JavaScript. .

No responses yet