Table of content:

Tired of bulky if-else statements? JavaScript's ternary operator offers a powerful solution. This handy tool lets you condense complex conditional logic into a single line, making your code cleaner, more elegant, and more efficient.

In this article, we'll take a deep dive into the ternary operator, understanding its syntax and showcasing real-world examples to help you understand how it works to harness its full potential.

What is A Ternary Operator?

A ternary operator is a conditional operator in JavaScript that evaluates a conditional expression and returns either a truthy or falsy value.

To understand how this works, let's take a closer look at its syntax below:

conditionalExpression ? truthyValue : falsyValue

From the syntax above, the condionalExpression is the expression that serves as the evaluation point, determining either a truthy or falsy value.

Following the ? (question mark), the value provided is returned in case the expression evaluates to truthy, whereas the value following the : (colon) is returned if the expression results in a falsy outcome.

The truthyValue and falsyValue can be anything in JavaScript. It can encompass various entities such as functions, values stored in variables, objects, numbers, strings, and more. The ternary operator grants you the flexibility to return any desired value, offering versatility in your code.

How to Use the Ternary Operator

Now that we've examined the syntax and its functionality, let's explore how to use the ternary operator to deepen our understanding.

Consider this scenario: we're building a gaming platform that only allows users who are aged 18 and above. We'll design a function to check a user's age. If they're under 18, they'll be denied access; otherwise, they'll gain entry to the platform.

function canAccessPlatform(age) {
  const shouldAccess = age >= 18 ? true : false;

  return shouldAccess;
}

From the code snippet above, we created a function, canAccessPlatform, which evaluates whether a user, represented by their age parameter, meets the requirement to access the platform.

It utilizes a ternary operator to determine if the age is 18 or older, assigning true to shouldAccess if the condition is met, and false otherwise. Finally, it returns the value of shouldAccess, indicating whether the user can access the platform or not.

If the age is 18 or older, the expression becomes true, so the operator returns true after the ?. Otherwise, it returns false. This result is saved in a variable and then returned from the function.

While this basic use case simplifies code and improves readability by replacing unnecessary if-else blocks, it's important to use it sparingly to avoid cluttering and complicating your code. Later, we'll discuss best practices for using the ternary operator.

Here's another example illustrating the use of the ternary operator. We'll create a function to determine whether a number is even or odd. Check out the code snippet below:

function checkEvenOrOdd(number) {
  const result = number % 2 === 0 ? "even" : "odd";
  return result;
}

// Usage:
console.log(checkEvenOrOdd(4)); // Output: "even"
console.log(checkEvenOrOdd(7)); // Output: "odd"

From the code snippet above:

  • We define a function checkEvenOrOdd that takes a number parameter.
  • Inside the function, we use the ternary operator to check if the number is even or odd.
  • If the number modulo 2 equals 0 (meaning it's divisible by 2 with no remainder), then the condition evaluates to true, and the string "even" is assigned to the result variable.
  • If the condition evaluates to false (meaning the number is odd), the string "odd" is assigned to result.
  • Finally, the function returns the value of result, which indicates whether the number is even or odd.

This code shows how the ternary operator quickly checks if a number is even or odd, making the code easier to read and understand.

How to Refactor if-else Statements to Ternary Operator

An advantage of the ternary operator is avoiding unnecessary if-else blocks, which can complicate code readability and maintenance. In this section, we'll refactor some if-else statements into ternary operations, providing a clearer understanding of how to use ternary operators effectively.

Let's start with our first example:

function decideActivity(weather) {
  let activity;

  if (weather === "sunny") {
    activity = "go out";
  } else {
    activity = "stay in";
  }

  console.log(activity);
}

// Usage
console.log(decideActivity("raining")); // Output: "stay in"
console.log(decideActivity("snowing")); // Output: "stay in"
console.log(decideActivity("sunny")); // Output: "go out"

This function, decideActivity, takes a weather parameter and determines the appropriate activity based on the weather conditions.

If the weather is "sunny", it suggests to "go out". Otherwise, it advises to "stay in". When we call the function with different weather conditions like "raining" or "snowing", it outputs the corresponding activity recommendation using console.log().

For instance, calling decideActivity("raining") will output "stay in". Similarly, decideActivity("snowing") also outputs "stay in". When decideActivity("sunny") is called, it outputs "go out". This straightforward function helps decide on activities based on the weather conditions provided.

Now, we can refactor these blocks of code to make them look simpler and neater. Let's see how to do that below:

function decideActivity(weather){
   const activity = weather === "sunny" ? "go out" ? "stay in";
   
   console.log(activity)

}

// Usage
console.log(decideActivity("raining")); // Output: "stay in"
console.log(decideActivity("snowing")); // Output: "stay in"
console.log(decideActivity("sunny")); // Output: "go out"

From the code sample above, this function, decideActivity, uses the ternary operator to quickly determine the activity based on the weather conditions. It checks if the weather is "sunny" and assigns "go out" if true, otherwise "stay in".

We've simplified the if-else statements into a one-liner ternary operator. This makes our code cleaner, clearer, and easier to read.

Let's take a look at another example:

function checkNumber(number) {
  let result;
  if (number > 0) {
    result = "positive";
  } else {
    result = "non-positive";
  }
  return result;
}

// Usage
console.log(checkNumber(5)); // Output: "positive"
console.log(checkNumber(-2)); // Output: "non-positive"

Let's explain what the code above is doing:

  • Function Definition: We begin by defining a function named checkNumber that takes a single parameter called number.
  • Variable Declaration: Inside the function, we declare a variable named result without assigning any value to it yet. This variable will store the result of our check.
  • Conditional Statement (if-else): We have a conditional statement that checks whether the number parameter is greater than 0.
  • If the condition is true (meaning the number is positive), we assign the string "positive" to the result variable.
  • If the condition is false (meaning the number is not positive, (meaning it is either negative or zero), we assign the string "non-positive" to the result variable.
  • Return Statement: Finally, we return the value stored in the result variable.
  • Function Calls: We then call the checkNumber function twice with different arguments: 5 and -2.

When we call checkNumber(5), the function returns "positive", which is then logged to the console.

Similarly, when we call checkNumber(-2), the function returns "non-positive", which is again logged to the console.

This function efficiently determines whether a number is positive or non-positive and provides the appropriate result based on the condition.

Let's simplify and improve the code by rewriting it using a ternary operator.

function checkNumber(number) {
  const result = number > 0 ? "positive" : "non-positive";
  return result;
}

// Usage
console.log(checkNumber(5)); // Output: "positive"
console.log(checkNumber(-2)); // Output: "non-positive"

Great job! By refactoring the function and utilizing the ternary operator for conditional evaluation, we've achieved cleaner, more concise, and readable code.

This code, using the ternary operator, feels more concise and elegant. It efficiently determines if a number is positive or non-positive, making the code cleaner and easier to understand. When we call checkNumber(5), it returns "positive",  while checkNumber(-2) returns "non-positive". Overall, the ternary operator enhances the code's readability.

Conclusion

As we conclude this article, you've gained a comprehensive understanding of the ternary operator—its application in daily coding tasks, converting if/else statements, chaining operators, and best practices. I'm confident that you've acquired valuable insights that will enhance your coding practices using the ternary operator.