JavaScript Ternary Operator: A Concise Decision-Making Tool

By Saheb Sutradhar - Updated On 05-03-2024

JavaScript Ternary Operator: A Concise Decision-Making Tool

 

The JavaScript ternary operator provides a compact way to make decisions based on conditions. It’s often used as an alternative to traditional if...else statements. Let’s dive into the details of this powerful operator and explore its various use cases.

Syntax

The basic syntax of the ternary operator:

condition ? exprIfTrue : exprIfFalse
  • condition: An expression whose value determines the outcome.
  • exprIfTrue: An expression executed if the condition evaluates to a truthy value.
  • exprIfFalse: An expression executed if the condition is falsy.

Key Characteristics

  1. Three Operands: The ternary operator takes three operands—the condition, the true expression, and the false expression.
  2. Shorthand: It’s a concise way to check a condition and return a value based on it.
  3. Right-Associative: The ternary operator is right-associative, allowing for chaining multiple conditions.

Basic Usage

Suppose we want to determine whether someone is old enough to drink. We can use the ternary operator like this:

const age = 20;
const beverage = age >= 21 ? "Beer" : "Juice";
console.log(beverage); // Output: "Juice"

Handling Null Values

The ternary operator is handy for handling null values. Consider the following function:

const greeting = (person) => {
  const name = person ? person.name : "stranger";
  return `Howdy, ${name}`;
};

console.log(greeting({ name: "Alice" })); // Output: "Howdy, Alice"
console.log(greeting(null)); // Output: "Howdy, stranger"

Multiple Conditions (Chaining)

You can chain ternary operators to handle more complex scenarios:

function example() {
  return condition1 ? value1 : condition2 ? value2 : condition3 ? value3 : value4;
}

This is equivalent to the following if...else chain:

function example() {
  if (condition1) {
    return value1;
  } else if (condition2) {
    return value2;
  } else if (condition3) {
    return value3;
  } else {
    return value4;
  }
}

JavaScript ternary operator Examples

Let’s explore more examples of using the JavaScript ternary operator to make your code concise and expressive:

1. Score Rating:

Suppose you have a numeric score, and you want to determine the rating based on whether the score is above 70. Here’s how you can use the ternary operator:

const score = 80;
const scoreRating = score > 70 ? "Excellent" : "Do better";
console.log(scoreRating); // Output: "Excellent"

2. Redirect URL:

Imagine you’re building a web application, and you need to decide the next URL based on whether the user is authenticated. The ternary operator can handle this elegantly:

let authenticated = true;
let nextURL = authenticated
  ? (alert("You will redirect to admin area"), "/admin")
  : (alert("Access denied"), "/403");

In this example, if authenticated is true, the first expression executes (redirecting to the admin area), otherwise, the second expression executes (showing an access denied message).

3. Pass or Fail:

Let’s create a function that checks whether a student has passed an exam based on their marks:

const checkPassOrFail = (marks) => (marks >= 40 ? "pass" : "fail");

console.log(checkPassOrFail(78)); // Output: "pass"
console.log(checkPassOrFail(30)); // Output: "fail"

The ternary operator succinctly handles the pass/fail decision.

What is the difference between nullish coalescing and ternary operator?

Nullish Coalescing Operator (??):

  • The nullish coalescing operator distinguishes between:

    • Nullish values: These include null and undefined.
    • Falsy but defined values: Examples are false0, and an empty string ('').
  • It returns the right-hand value only if the left-hand value is null or undefined.

  • Useful for providing default values when dealing with null or undefined variables.

Example:

const x = null;
const y = x ?? 'default'; // y will be 'default'

Ternary Operator (? :):

  • The ternary operator checks whether the condition is truthy or falsy.

  • If the left-hand value is falsy It uses the right-hand value.

  • Commonly used for conditional expressions.

Example:

const a = 0;
const b = a ? 'truthy' : 'falsy'; // b will be 'falsy'

Conclusion

The JavaScript ternary operator is a powerful tool for concise decision making. Whether you’re handling null values or creating conditional chains, mastering this operator can lead to cleaner and more efficient code. Happy coding! 🚀

 

 

 

codelearningpoint © 2024