How to Use the Ternary Operator in JavaScript

Lauren Farrell



Like all programming languages, there are multiple ways to achieve the same output in JavaScript. However, in some cases, one method is far more efficient and requires less code than others. That includes the JavaScript ternary operator.

person using javascript ternary operator in their code

Here, you’ll learn what this function does and how you can use it in your programming.

Download Now: An Introduction to JavaScript  [Free Guide]

There are a few ways to achieve this result in JavaScript, but the ternary operator is considered a concise method. It uses less code than other methods and is a faster way to execute a conditional output in JavaScript.

How to Use a JavaScript Ternary Operator

A ternary operator evaluates conditions to present a true or false value, but with more concise syntax and parameters than other methods.

The syntax of a ternary operator is as follows:

condition ? exprIfTrue : exprIfFalse

The condition is what your code will evaluate to decide the correct output. The exprIfTrue is the expression you will get if the condition is evaluated as true. The exprIfFalse is the expression you will get if the condition is evaluated as false.

JavaScript Ternary Operator Examples

JavaScript Ternary Operator vs. If-Else Statements

You might already be familiar with the if-else statement in JavaScript. Using this method, your script can assess conditions and present corresponding expressions based on these conditions.

Here is an example of an if-else statement:

let result = 10; let result; if(result >= 5){ result = "You have passed the test"; } else { result = "You have failed the test"; } console.log(result);

Let’s say someone takes the test and gets a score of 2. In this instance, the output will be “You have failed the test.”

As you can see from this example, if-else statements are very clear and easy to interpret, but they require multiple lines of code.

Here’s how the if-else example above looks when written as a ternary operator instead:

let result = 10; let result = result >= 5 ? "You have passed the test" : "You have failed the test"; console.log(result);

The (?) represents the endpoint of the conditions the ternary operator should check. In this instance, the operator is being asked to check whether the result is greater than 5. This is the first operand.

Everything after the (?) represents the expressions available as results. The second operand is the exprIfTrue, or "You have passed the test." The third operand is the exprIfFalse, or "You have failed the test."

The end result is the same as the if-else statement, but the amount of code is vastly reduced.

Using JavaScript Ternary Operator for Multi-Line Expressions

Many situations require more complex operators than the first example above. But you can easily use a ternary operator for more complicated scenarios with multi-line expressions.

Let’s compare an if-else and a ternary operator statement again to demonstrate using ternary operators for multi-line expressions.

Take this statement for example:

const score = 10; let results; if (score <= 8) { results = true; console.log("Test Failed"); } else { results = false; console.log("Test Passed"); } console.log(results);

While this is easy to interpret, there’s a lot going on. Here is what the same statement looks like using a ternary operator:

score <= 8 ? ((results = true), console.log("Test Failed")) : ((results = false), console.log("Test Passed"));

It’s as simple as using brackets to hold the expressions and separating them with commas.

So, why wouldn’t you use a ternary operator in these situations all the time?

It really comes down to how easy it needs to be to interpret your code. If you’re working on large teams or need to hand a project off to other developers, ternary operators can sometimes get a little confusing. That’s why, even though they’re shorter and more simple to write, most people stick with an if-else statement for anything other than a single-line expression.

Using One Ternary Operator Inside Another

Placing one ternary operator inside another is also known as a nested ternary operator. In the examples above, we were using ternary statements to determine whether someone had passed or failed a test.

But what if you’re dealing with multiple grades and scoring brackets? That’s where a nested ternary operator can be useful.

Here is how it would look:

let score = 100; let results = score >= 85 ? "A" : score >= 70 ? "B" : score >= 55 ? "C" : score >= 40 ? "D" : "F"; console.log(`Here is your test grade ${results}`);

Each subsequent ? represents its own ternary operator within the overall operator represented by score >= 85 ? "A".

Once again, it’s efficient. But it’s not that easy to interpret at a glance. Here is how the same statement would look as an if-else:

let score = 100; let results; if (score >= 85) { results = "A"; } else if (score >= 70) { results = "B"; } else if (score >= 55) { results = "C"; } else if (score >= 40) { results = "D"; } else { results = "F"; } console.log(`Here is your test grade ${results}`);

There’s no doubt that this is a much longer way to write the statement. But colleagues and anyone else reading your code will be able to understand and amend it more quickly.

Working With Ternary Operators

Ternary operators have their place in JavaScript coding. However, they’re certainly not a replacement for if-else statements, or others like switch statements, in all scenarios.

But sometimes, if-else statements create an unnecessary amount of writing. Ternary operators can be used in cases where it would be just as simple to interpret as an if-else statement. When two statements can be used interchangeably like this, it’s up to your best judgment which is preferable. Keeping a balance between ease of interpretation and code space in mind will generally lead you to the right one.

New Call-to-action

Topics: Javascript

Related Articles

We're committed to your privacy. HubSpot uses the information you provide to us to contact you about our relevant content, products, and services. You may unsubscribe from these communications at any time. For more information, check out our Privacy Policy.

Learn more about one of the world's most popular programming languages.