Ad space (banner)
🟨JavaScript Lessons
Lesson 16 / 69

The Ternary Operator

In this lesson you'll learn how to write JavaScript's ternary operator so you can express simple conditionals concisely in a single line. This is for people searching "JavaScript ternary operator usage" or "JavaScript one-line if."

Writing condition ? valueIfTrue : valueIfFalse lets you express a simple if statement in one line. This is called the ternary operator. It's well suited for short branches, like "decide whether someone is an adult or a minor and pick a message on the spot." Instead of spending four lines on if...else, its biggest advantage is bundling a variable assignment together with a conditional into a single line.

The sample code uses the ternary operator age >= 20 ? "Adult" : "Minor" to switch which string gets assigned to the message variable depending on the value of age. It helps to remember the shape of the syntax: the condition comes before the ?, and the true-value and false-value sit on either side of the : — that makes both reading and writing it much smoother.

The trick is to only use it for a simple two-way decision — forcing a complicated condition into it just makes things harder to read. Nesting ternary operators to express several stages of branching tends to produce code whose meaning isn't obvious at a glance, so it's safer to use an if statement for complex branching. Keep in mind the rule: "ternary operators only for short, simple two-way choices."

In real development, the ternary operator comes up frequently for small value switches — swapping the text displayed on screen depending on a condition, or deciding on a fallback value when something hasn't been set yet. Whether something should be written as an if statement or is fine as a ternary is a point that often comes up in code review discussions about readability.

The condition part can also combine logical operators (&& and ||) in addition to comparison operators, letting you fit even somewhat complex checks into one line. But if it starts getting hard to read, it's important to make the judgment call to switch back to an if statement rather than forcing the ternary operator.

The ternary operator can also be embedded directly inside a template literal. Writing something like `You are ${age >= 20 ? "an adult" : "a minor"}` lets you complete a conditional text swap entirely within one string.

JavaScript
OUTPUT

💡 Anything passed to console.log() appears in the output below.

Ad space (banner)
Ad space (in-article)