Pro: Readability

While plenty of people talk about the readability problems with misused ternary operators, there are also situations where using a full if/else would be annoyingly bulky, spreading a simple statement across five lines, and significantly reducing readability. Here are some sample statements pulled from a project I'm working on:

bg_2d.fillStyle = is_in_bounds(x, y) ? grid_colors[x][y] : "#ffffff";
const diagonal_slowdown = is_diagonal() ? Math.SQRT2 : 1;
const color = (team == "red") ? "#ff0000" : "#0000ff";

When you have a simple situation where you have two things to pick from based on a condition, which happens all the time, ternary is perfect. Having a short syntax for ternary massively improves readability in these situations.

Answer from rydwolf on Stack Exchange
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Operators › Conditional_operator
Conditional (ternary) operator - JavaScript | MDN
An expression which is executed if the condition evaluates to a truthy value (one which equals or can be converted to true).
🌐
Programiz
programiz.com › javascript › ternary-operator
JavaScript Ternary Operator (with Examples)
In this tutorial, you will learn about the conditional/ternary operator in JavaScript with the help of examples.
🌐
W3Schools
w3schools.com › js › js_if_ternary.asp
JavaScript Conditional Ternary Operator
The conditional operator is a shorthand for writing conditional if...else statements. It is called a ternary operator because it takes three operands.
🌐
W3Schools
w3schools.com › c › c_conditions_short_hand.php
C Short Hand If ... Else (Ternary Operator)
C Examples C Real-Life Examples C Exercises C Quiz C Code Challenges C Compiler C Syllabus C Study Plan C Interview Q&A C Certificate ... There is also a short-hand if...else, known as the ternary operator because it uses three operands.
Top answer
1 of 16
771

This is a one-line shorthand for an if-else statement. It's called the conditional operator.1

Here is an example of code that could be shortened with the conditional operator:

var userType;
if (userIsYoungerThan18) {
  userType = "Minor";
} else {
  userType = "Adult";
}

if (userIsYoungerThan21) {
  serveDrink("Grape Juice");
} else {
  serveDrink("Wine");
}

This can be shortened with the ?: like so:

var userType = userIsYoungerThan18 ? "Minor" : "Adult";

serveDrink(userIsYoungerThan21 ? "Grape Juice" : "Wine");

Like all expressions, the conditional operator can also be used as a standalone statement with side-effects, though this is unusual outside of minification:

userIsYoungerThan21 ? serveGrapeJuice() : serveWine();

They can even be chained:

serveDrink(userIsYoungerThan4 ? 'Milk' : userIsYoungerThan21 ? 'Grape Juice' : 'Wine');

Be careful, though, or you will end up with convoluted code like this:

var k = a ? (b ? (c ? d : e) : (d ? e : f)) : f ? (g ? h : i) : j;

1 Often called "the ternary operator," but in fact it's just a ternary operator [an operator accepting three operands]. It's the only one JavaScript currently has, though.

2 of 16
183

I want to add some to the given answers.

In case you encounter (or want to use) a ternary in a situation like 'display a variable if it's set, else...', you can make it even shorter, without a ternary.


Instead of:

var welcomeMessage  = 'Hello ' + (username ? username : 'guest');

You can use:

var welcomeMessage  = 'Hello ' + (username || 'guest');

This is Javascripts equivallent of PHP's shorthand ternary operator ?:

Or even:

var welcomeMessage  = 'Hello ' + (username || something || maybethis || 'guest');

It evaluates the variable, and if it's false or unset, it goes on to the next.

🌐
freeCodeCamp
freecodecamp.org › news › ternary-operator-javascript-if-statement-tutorial
Ternary Operator JavaScript If Statement Tutorial
January 25, 2021 - The conditional operator – also known as the ternary operator – is an alternative form of the if/else statement that helps you to write conditional code blocks in a more concise way.
🌐
SitePoint
sitepoint.com › blog › javascript › quick tip: how to use the ternary operator in javascript
Quick Tip: How to Use the Ternary Operator in JavaScript — SitePoint
November 6, 2024 - ... The ternary operator in JavaScript is a shorthand way of writing an if-else statement. It is called the ternary operator because it takes three operands: a condition, a result for true, and a result for false.
Find elsewhere
🌐
Wikipedia
en.wikipedia.org › wiki › Ternary_conditional_operator
Ternary conditional operator - Wikipedia
January 27, 2026 - In computer programming, the ternary conditional operator is a ternary operator that evaluates to one of two values based on a Boolean expression. The operator is also known as conditional operator, ternary if, immediate if, or inline if (iif). Although many ternary operators are theoretically ...
🌐
Reddit
reddit.com › r/learnjavascript › ternary operator
r/learnjavascript on Reddit: Ternary operator
May 22, 2022 - We can now convert this into a Ternary Operator. let score = 10; let grade = score > 89 ? 'A' : score > 79 ? 'B' : score > 69 ? 'C' : score > 59 ?
🌐
DEV Community
dev.to › wizdomtek › mastering-the-javascript-ternary-operator-a-comprehensive-guide-5388
Mastering the JavaScript Ternary Operator: A Comprehensive Guide - DEV Community
October 27, 2024 - The expressions involve side effects or multiple statements. Readability is compromised. The JavaScript ternary operator is a powerful tool for writing cleaner and more concise code.
🌐
W3Schools
w3schools.com › js › js_comparisons.asp
JavaScript Comparison Operators
All the comparison operators above can also be used on strings: let text1 = "A"; let text2 = "B"; let result = text1 < text2; Try it Yourself » ... Comparing data of different types may give unexpected results. When comparing a string with a number, JavaScript will convert the string to a number when doing the comparison.
🌐
W3Schools
w3schools.com › react › react_es6_ternary.asp
React ES6 Ternary Operator
The ternary operator is a simplified conditional operator like if / else. Syntax: condition ? <expression if true> : <expression if false> ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an ...
🌐
Reddit
reddit.com › r/learnprogramming › javascript ternary operator syntax with object
r/learnprogramming on Reddit: Javascript ternary operator syntax with object
September 9, 2023 -

Hello, i got some issues with the syntax for this line of code:

counter === null ? counter = {wins: 0, losses:0, ties:0};

It tells me there is some issue with the ';'. I never had such a problem with ternary operators before, it seems like to be related with the object inside of it. what would be the right declaration of it?

Thanks

🌐
Refine
refine.dev › home › blog › tutorials › how to use the javascript ternary operator
How to Use the JavaScript Ternary Operator | Refine
October 8, 2024 - As we can see, the Ternary Operator places the conditional expression before the ? and accepts the executable expressions as two other operands that are separated by a colon, :. If the conditionalExpression evaluates to a truthy value, exprIfTruthy is executed. If it evaluates to a falsy value, exprIfFalsy is executed. In JavaScript, a truthy value corresponds to a value that is considered equivalent to true had that been converted to a Boolean.
🌐
Reddit
reddit.com › r/learnjavascript › question on if/when to use ternary operators?
r/learnjavascript on Reddit: Question on if/when to use Ternary Operators?
December 29, 2024 -

So i am completly new to programming and learning thru codecademy.

I just got thru all the lessons about if else statements and when/how to use them but in their next lession they talk about Ternary Operator basically being a "shot handed" version of wirting an if else statement (if I am understanding that correctly) if I am understanding it correctly then my question is, is one more "professional" then the other or is it just based on what your coding or what lets say your boss is asking you to code

The other reason I ask is I want to devlope good habits now vs later down the road so using the example below is it I guess from a "real world" working senario is it better to use one over the other

For example; I know this is a very genaric and basic example but

let nightTime = true

if (nighTime) {
    console.log('Nightime');
} else {
    console.log('Daytime')
}

vs

nightTime
    ? console.log('Nighttime')
    : console.log('Daytime');
🌐
RunJS
runjs.app › blog › using-the-ternary-operator-in-javascript
Using the Ternary Operator in JavaScript
October 14, 2022 - If the condition is truthy, then the first expression is executed, or if the condition is falsy, then the second expression is executed. ... The ternary operator is particularly useful for conditional assignment. This is because you can initialize and assign a variable in a single statement.
🌐
DEV Community
dev.to › nicm42 › ternary-operators-in-javascript-go5
Ternary operators in JavaScript - DEV Community
December 12, 2021 - Ternary operators are also known as conditional operators. Basically, they put an if else statement... Tagged with javascript.
🌐
Mimo
mimo.org › glossary › javascript › ternary-operator
JavaScript Ternary Operator: Syntax, Usage, and Examples
Instead of using a full if...else statement, you can evaluate a condition and return a value in a single line. The ternary operator JavaScript syntax is especially useful for assigning values or returning expressions based on a condition—making your code cleaner and more expressive.
🌐
Scaler
scaler.com › home › topics › javascript › javascript ternary operator
JavaScript Ternary Operator - Scaler Topics
February 19, 2024 - ... The below table explains that what is the minimum version of a specific browser required to support ternary operator: A Ternary Operator in Javascript is a special operator which accepts three operands.