Menu Close

Ternary operator in javascript

Ternary operator in javascript

There are many operators in JavaScript, one of which is the ternary operator.

There is also a short-hand if else, which is known as the ternary operator because it consists of three operands.

It can be used to replace multiple lines of code with a single line, and is most often used to replace simple if else statements

What is the ternary operator

The ternary operator is a conditional operator which evaluates either of two expressions – a true expression and a false expression – based on a conditional expression that you provide.


codition ? true expression : false expression 

You have the condition which returns a truthy or falsy value. Truthy values here include true, and non-falsy values. Falsy values here include false, null, 0, and so on.

After the condition, you have the question mark followed by the true expression. This expression is executed if the condition evaluates to true.

After the true expression, you have a colon, followed by the false expression. This expression is executed if the condition evaluates to false.


How to Use the Ternary Operator in Place of if..else Statements

The ternary operator can be a good replacement for if..else statements in some cases. It allows you to write cleaner, and easier-to-read lines of code if used well.

let’s see an example:

const score = 70
let scoreRating

if (score > 60) {
  scoreRating = "Good"
} else {
  scoreRating = "Do better"

// "Good" 

In this example, we have a score variable with 70 and a scoreRating variable. Then we have an if..else statement that checks score>60. If this condition evaluates true, the scoreRating variable is assigned “Good”, else, it is assigned “Do better”.

We can improve this code using ternary operator. Here’s see below and remember syntax of ternary operator.

you have the condition, a question mark, the true expression, a colon, and finally a false expression. Let’s look at this in code:

const score = 70

const scoreRating =
  score >60 ? "Good" : "Do better"

// Good 

This is how we use the ternary operator. The true and false expressions here are strings that will be returned to the scoreRating variable depending on our condition score>60

The true and false expressions can be any kind of expression from function executions to arithmetic operations and so on.

Let’s an example with a function execution:

function printfail() {
  console.log("not good result")
  return "failure"

function printSuccess() {
  console.log("Nice result")
  return "success"

const pass = true;
const result = pass ? printSuccess() : printfail()
// Nice result (console.log executed)

Here, you can see that  the condition returns true, the true expression, printsuccess() is executed which prints “Nice result” to the console. And as the true expression returns “success”, you can see that value assigned to the result variable.

Posted in JavaScript, Web Technologies

You can also read...