Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 21

Ternary Operator for Concise Conditionals

This lesson is built with resources from youtube.com, freecodecamp.org and 1 more site.

Hello! In our last lesson, we learned how to create branching logic using if, else, and else if. This is a powerful way to control program flow, but sometimes, for simple, two-path decisions, it can feel a little verbose.

Today, we'll learn about a more compact alternative: the ternary operator. This lesson will show you how to use this operator (? :) to write concise, single-line conditional expressions. A key insight you'll gain is understanding why this is possible—because the ternary operator is an expression that resolves to a value, unlike the if statement which performs an action. This distinction is fundamental and will sharpen your understanding of JavaScript's building blocks.

What is the Ternary Operator?

The ternary operator is the only operator in JavaScript that takes three parts (or "operands"):

  1. A condition to be evaluated (true or false).
  2. A value to return if the condition is true.
  3. A value to return if the condition is false.

The syntax looks like this:

condition ? valueIfTrue : valueIfFalse

Think of the ? as "was this condition true?" and the : as "otherwise...".

To help you visualize this flow, here's a flowchart that perfectly illustrates the logic.

Ternary Operator Flowchart
This flowchart shows how the operator first evaluates a condition. If the condition is true, it executes one expression; if false, it executes another. The result of the chosen expression becomes the final value.

From if...else to Ternary

Let's take a typical if...else statement that assigns a value to a variable:

let age = 20;
let canDrink;

if (age >= 18) {
  canDrink = "Yes, you can have a drink.";
} else {
  canDrink = "Sorry, you are too young.";
}

console.log(canDrink); // "Yes, you can have a drink."

This works perfectly, but it takes up several lines to do one simple thing: assign a value to canDrink.

Now, let's refactor this using the ternary operator:

let age = 20;

const canDrink = age >= 18 ? "Yes, you can have a drink." : "Sorry, you are too young.";

console.log(canDrink); // "Yes, you can have a drink."

Notice a few things:

  • It's a single, elegant line of code.
  • We can declare canDrink with const because the value is assigned immediately upon declaration and never changed. This is a common and excellent practice.
  • The logic is identical to the if...else block.

This visual comparison makes the transformation crystal clear.

If Else Statement vs. Ternary Operator
This image directly contrasts a multi-line 'if-else' block with a single-line ternary expression, both achieving the same result of assigning a value based on a condition.

The following video provides a great introduction to this concept and shows how the result of a ternary operation can be stored in a variable.

#9 JavaScript Ternary Operator | JavaScript for Beginners

The video '#9 JavaScript Ternary Operator' from Programiz clearly explains the basic syntax and demonstrates how to assign the outcome of a ternary expression to a variable.

Watch from 00:00 to 00:51 to understand the syntax and then from 02:04 to 03:30 to see how to store the resulting value.


The "Why": Expressions vs. Statements

You might be wondering why the ternary operator can be used directly in an assignment (const result = ...) while an if block cannot. This goes to the core of your "deep theory" preference.

In JavaScript, there is a fundamental difference between expressions and statements:

  • An expression is a piece of code that evaluates to (or "resolves to") a single value.
    • Examples: 2 + 2 (resolves to 4), age >= 18 (resolves to true or false), myFunction() (resolves to whatever the function returns).
  • A statement is an instruction that performs an action. It does not resolve to a value.
    • Examples: let x = 10;, if (condition) { ... }, for (let i=0; i<5; i++) { ... }.

The ternary operator is an expression. This is its superpower. Because it resolves to a value, you can use it anywhere a value is expected: assigning it to a variable, passing it as a function argument, or returning it from a function.

The if...else block is a statement. It directs the flow of execution but doesn't produce a value itself. That's why you can't write const result = if (x > 10) { "greater" } else { "less" }. It's grammatically incorrect in JavaScript.

This distinction is a cornerstone of functional programming patterns in JavaScript, which you'll encounter as you progress. Understanding it now gives you a significant advantage.

Rethinking the JavaScript ternary operator

The following article, 'Rethinking the JavaScript ternary operator,' has a brilliant section explaining this very concept. Focusing on this part will give you a deeper appreciation for the operator's role.

Please read the section that starts with 'This is because if statements and ternaries are different' and ends just before 'In another sense, though, those two examples are quite different.' This part clearly defines the difference between statements and expressions, which is the key theoretical takeaway for this lesson.


When to Use (and When NOT to Use) the Ternary Operator

Just because you can use the ternary operator doesn't mean you always should. The primary goal is readability.

The video below is an excellent guide on the best and worst use cases for the ternary operator.

Learn Ternary Operators In 9 Minutes

The video 'Learn Ternary Operators In 9 Minutes' by Web Dev Simplified perfectly breaks down the practical do's and don'ts.

Please watch the entire video. It's short and packed with value. Pay close attention to: The ideal use case: assigning a value to a single variable (01:12). The bad use case: performing actions or 'side effects' instead of returning a value (04:11). The ugly use case: nesting multiple ternaries, which destroys readability (05:48).

Summary of Best Practices:

  1. DO use it for simple conditional assignments. This is the ideal scenario where it makes code cleaner and more concise.
  2. AVOID using it to perform actions (or "side effects"), like calling functions that don't return values (console.log, DOM manipulation). An if...else statement is much clearer for actions.
  3. NEVER nest ternary operators. While technically possible, it creates code that is incredibly difficult to read and debug. An if...else if...else chain is always superior for multi-condition logic. As the video mentions, code should be easy for humans to understand, not just short.
Test your understanding!

You have a function getFee(isMember) that should return a fee amount. If isMember is true, the fee is $2.00. If false, the fee is $10.00.

Rewrite the following if...else statement as a single line using the ternary operator.

function getFee(isMember) {
  let fee;
  if (isMember) {
    fee = "$2.00";
  } else {
    fee = "$10.00";
  }
  return fee;
}
Show answer
function getFee(isMember) {
  return isMember ? "$2.00" : "$10.00";
}

// How it works:
// The function immediately returns the result of the ternary expression.
// If `isMember` is true, the expression resolves to "$2.00".
// If `isMember` is false, the expression resolves to "$10.00".

Chaining Ternaries (The else if Equivalent)

While heavily discouraged for readability reasons, it's useful to recognize the syntax for a chained ternary, which mimics an if...else if...else structure.

How to Use the Ternary Operator in JavaScript

The article 'How to Use the Ternary Operator in JavaScript' from freeCodeCamp has a good section that shows how chaining works, with clear examples.

Read the section titled 'How to Chain Ternary Operators'. Look at the examples to understand how one ternary can be nested in the 'false' part of another to create a chain. This will help you identify this pattern if you see it in other people's code.

Here's an example from the article:

// Using if...else if...else (CLEAR and PREFERRED)
function checkNumber(number) {
  if (number > 0) {
    return "Positive";
  } else if (number === 0) {
    return "Zero";
  } else {
    return "Negative";
  }
}

// Using a chained ternary (COMPACT but HARDER to read)
function checkNumberTernary(number) {
  return number > 0 ? "Positive" : number === 0 ? "Zero" : "Negative";
}

As you can see, the second version is harder to parse at a glance. For anything more than a simple true/false decision, a standard if statement is your best friend.


Conclusion

Great job! You've added another powerful tool to your JavaScript toolkit. The ternary operator, when used appropriately, can make your code more elegant and concise.

Key Takeaways:

  • The ternary operator (? :) is a compact shorthand for a simple if...else statement.
  • Its syntax is condition ? valueIfTrue : valueIfFalse.
  • Crucially, it is an expression, meaning it resolves to a value. This is why it's so useful for conditional assignments.
  • The best use case is assigning one of two values to a variable.
  • For the sake of readability, you should avoid using it for executing actions (side effects) or for complex, nested logic.

Next Up:

We've now covered if...else if...else and the ternary operator. But what if you need to check one variable against a dozen different possible values? A long if...else if chain can get clunky. In the next lesson, we'll explore the switch statement, a control structure designed specifically for that scenario.