DEV Community

Cover image for Beyond If-Else: JavaScript's Ternary Operator Explained
Harshal Ranjhani for CodeParrot

Posted on • Originally published at codeparrot.ai

1 1 1 1 1

Beyond If-Else: JavaScript's Ternary Operator Explained

If you've been coding in JavaScript for a while, you've probably come across situations where you needed to choose between two values based on a condition. The typical way to handle this is using an if-else statement. But what if I told you there's a more concise way to do this? Enter the ternary operator.

The ternary operator (also known as the conditional operator) is one of those little JavaScript features that can make your code cleaner and more readable when used correctly. In this blog post, we'll take a deep dive into what the ternary operator is, how it works, and when you should (and shouldn't) use it.

What is the Ternary Operator?

The ternary operator is a conditional operator that takes three operands:

  1. A condition
  2. A result for when the condition is true
  3. A result for when the condition is false

It's called "ternary" because it uses three operands, unlike most operators which use one or two.

Here's the basic syntax:

condition ? expressionIfTrue : expressionIfFalse
Enter fullscreen mode Exit fullscreen mode

The operator evaluates the condition and returns one of the two expressions based on whether the condition is truthy or falsy.

How the Ternary Operator Works

Let's look at a simple example:

const age = 20;
const canVote = age >= 18 ? "Yes, can vote" : "No, cannot vote";
console.log(canVote); // Output: "Yes, can vote"
Enter fullscreen mode Exit fullscreen mode

In this example:

  • We check if age is greater than or equal to 18
  • If it is, we return "Yes, can vote"
  • If it's not, we return "No, cannot vote"

The value returned by the ternary operator is then assigned to the canVote variable.

Ternary operator visualization

Truthy and Falsy Values in JavaScript

Before we dive deeper, it's important to understand what "truthy" and "falsy" mean in JavaScript, as the ternary operator evaluates conditions based on these concepts.

In JavaScript, any value can be used in a condition. Values that evaluate to false are considered "falsy", and values that evaluate to true are considered "truthy".

Falsy Values:

  • false
  • 0
  • "" (empty string)
  • null
  • undefined
  • NaN

Truthy Values:

  • Everything else! Some examples:
    • true
    • Non-zero numbers (positive or negative)
    • Non-empty strings
    • Arrays (even empty ones)
    • Objects (even empty ones)
    • Functions

Let's see this in action with the ternary operator:

const emptyString = "";
const result = emptyString ? "String has content" : "String is empty";
console.log(result); // Output: "String is empty"

const nonEmptyArray = [1, 2, 3];
const arrayResult = nonEmptyArray ? "Array exists" : "Array doesn't exist";
console.log(arrayResult); // Output: "Array exists"
Enter fullscreen mode Exit fullscreen mode

Ternary Operator vs If-Else Statement

The ternary operator is essentially a shorthand for an if-else statement. Let's compare the two:

Using If-Else:

let message;
if (isLoggedIn) {
  message = "Welcome back!";
} else {
  message = "Please log in";
}
Enter fullscreen mode Exit fullscreen mode

Using Ternary Operator:

const message = isLoggedIn ? "Welcome back!" : "Please log in";
Enter fullscreen mode Exit fullscreen mode

As you can see, the ternary operator allows us to accomplish the same thing with much less code.

When to Use the Ternary Operator

The ternary operator shines in situations where:

  1. You need to choose between two values based on a condition
  2. You want to assign a value conditionally
  3. You need to return different values based on a condition
  4. You want to keep your code concise

Let's look at some common use cases.

Assigning Values Conditionally

// Without ternary
let discount;
if (isPremiumUser) {
  discount = 0.2; // 20% discount
} else {
  discount = 0.05; // 5% discount
}

// With ternary
const discount = isPremiumUser ? 0.2 : 0.05;
Enter fullscreen mode Exit fullscreen mode

Returning Values in Functions

// Without ternary
function getGreeting(name) {
  if (name) {
    return `Hello, ${name}!`;
  } else {
    return "Hello, guest!";
  }
}

// With ternary
function getGreeting(name) {
  return name ? `Hello, ${name}!` : "Hello, guest!";
}
Enter fullscreen mode Exit fullscreen mode

Conditional Rendering in React

If you work with React, you've probably used the ternary operator for conditional rendering:

return (
  <div>
    {isLoading 
      ? <LoadingSpinner /> 
      : <UserData data={userData} />
    }
  </div>
);
Enter fullscreen mode Exit fullscreen mode

Chaining Ternary Operators

You can also chain ternary operators to handle multiple conditions, similar to an if-else if-else statement. However, this can make your code harder to read if overused.

// Multiple conditions with ternary operators
const getAge = age => {
  return age < 13 ? "Child" 
       : age < 18 ? "Teenager"
       : age < 65 ? "Adult"
       : "Senior";
};

console.log(getAge(10)); // "Child"
console.log(getAge(15)); // "Teenager"
console.log(getAge(30)); // "Adult"
console.log(getAge(70)); // "Senior"
Enter fullscreen mode Exit fullscreen mode

While this works, it can become confusing quickly. For more complex conditions, consider using if-else or switch statements instead.

Advanced Use Cases

Handling Null or Undefined Values

The ternary operator can be used alongside the nullish coalescing operator (??) or logical OR (||) to provide default values:

// Using ternary with nullish coalescing
const username = userData?.name ? userData.name : "Anonymous";

// A cleaner version using nullish coalescing directly
const username = userData?.name ?? "Anonymous";
Enter fullscreen mode Exit fullscreen mode

Conditional Function Calls

// Call different functions based on a condition
const validateInput = isNumeric 
  ? validateNumber(input) 
  : validateString(input);

// Or execute a function conditionally
isDebugMode ? console.log("Debug info:", data) : null;
Enter fullscreen mode Exit fullscreen mode

In Template Literals

const greeting = `Hello, ${name ? name : "guest"}!`;

// Or even simpler with nullish coalescing
const greeting = `Hello, ${name ?? "guest"}!`;
Enter fullscreen mode Exit fullscreen mode

Performance Considerations

In terms of performance, the ternary operator and if-else statements are pretty similar. The JavaScript engine optimizes both quite well.

However, the ternary operator can potentially be slightly faster in some cases because:

  1. It's an expression rather than a statement, which can be optimized differently
  2. It involves less typing, which means less code to parse and execute

Here's a simple benchmark comparison:

// Testing if-else vs ternary performance
const iterations = 10000000;

console.time('if-else');
let resultIfElse;
for (let i = 0; i < iterations; i++) {
  if (i % 2 === 0) {
    resultIfElse = 'even';
  } else {
    resultIfElse = 'odd';
  }
}
console.timeEnd('if-else');

console.time('ternary');
let resultTernary;
for (let i = 0; i < iterations; i++) {
  resultTernary = i % 2 === 0 ? 'even' : 'odd';
}
console.timeEnd('ternary');
Enter fullscreen mode Exit fullscreen mode

The performance difference is usually negligible for most applications, so readability should be your primary concern.

Common Mistakes to Avoid

Overusing Chained Ternaries

// Hard to understand
const status = 
  type === 'user' ? 'regular' 
  : type === 'admin' ? 'full' 
  : type === 'guest' ? 'limited' 
  : 'none';

// Better as a switch or object lookup
const statusMap = {
  user: 'regular',
  admin: 'full',
  guest: 'limited'
};
const status = statusMap[type] || 'none';
Enter fullscreen mode Exit fullscreen mode

Forgetting That Ternary is an Expression

// This doesn't work as expected
condition ? doSomething() : doSomethingElse();

// You need to use the result or use if-else
const result = condition ? doSomething() : doSomethingElse();
// Or
if (condition) {
  doSomething();
} else {
  doSomethingElse();
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

The ternary operator is a powerful tool in JavaScript that can make your code more concise and readable when used appropriately. It's especially useful for simple conditional assignments, returns, and rendering.

However, like any tool, it's important to use it wisely. When conditions become complex or you need to execute statements rather than just return values, traditional if-else statements might be clearer.

By understanding when and how to use the ternary operator effectively, you'll be able to write more elegant and maintainable JavaScript code.

Happy coding!

Heroku

Deploy with ease. Manage efficiently. Scale faster.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

DEV is better (more customized, reading settings like dark mode etc) when you're signed in!

Okay