ternary operator "x ? y : z" in many programming languages, whose value is y if x evaluates to true and z otherwise
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 โ€ฆ Wikipedia
๐ŸŒ
Wikipedia
en.wikipedia.org โ€บ wiki โ€บ Ternary_conditional_operator
Ternary conditional operator - Wikipedia
2 days ago - A true ternary operator exists for arithmetic expressions: ((result = condition ? value_if_true : value_if_false)) ... Where condition can be any bash command. When it exits with success, the first echo command is executed, otherwise the second one is executed. The following code in C assigns result to the value of x if a > b, and otherwise to the value of y. This is the same syntax as in many related languages including C++, Java, JavaScript, and Dart.
๐ŸŒ
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.
๐ŸŒ
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 โ€บ 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.

๐ŸŒ
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
๐ŸŒ
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.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnjavascript โ€บ ternary operator
r/learnjavascript on Reddit: Ternary operator
May 20, 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.
๐ŸŒ
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

๐ŸŒ
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 ...
๐ŸŒ
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.
Top answer
1 of 6
199

Heh, there are some pretty exciting uses of ternary syntax in your question; I like the last one the best...

x = (1 < 2) ? true : false;

The use of ternary here is totally unnecessary - you could simply write

x = (1 < 2);

Likewise, the condition element of a ternary statement is always evaluated as a Boolean value, and therefore you can express:

(IsChecked == true) ? removeItem($this) : addItem($this);

Simply as:

(IsChecked) ? removeItem($this) : addItem($this);

In fact, I would also remove the IsChecked temporary as well which leaves you with:

($this.hasClass("IsChecked")) ? removeItem($this) : addItem($this);

As for whether this is acceptable syntax, it sure is! It's a great way to reduce four lines of code into one without impacting readability. The only word of advice I would give you is to avoid nesting multiple ternary statements on the same line (that way lies madness!)

2 of 6
24

The ternary style is generally used to save space. Semantically, they are identical. I prefer to go with the full if/then/else syntax because I don't like to sacrifice readability - I'm old-school and I prefer my braces.

The full if/then/else format is used for pretty much everything. It's especially popular if you get into larger blocks of code in each branch, you have a muti-branched if/else tree, or multiple else/ifs in a long string.

The ternary operator is common when you're assigning a value to a variable based on a simple condition or you are making multiple decisions with very brief outcomes. The example you cite actually doesn't make sense, because the expression will evaluate to one of the two values without any extra logic.

Good ideas:

this > that ? alert(this) : alert(that);  //nice and short, little loss of meaning

if(expression)  //longer blocks but organized and can be grasped by humans
{
    //35 lines of code here
}
else if (something_else)
{
    //40 more lines here
}
else if (another_one)  /etc, etc
{
    ...

Less good:

this > that ? testFucntion() ? thirdFunction() ? imlost() : whathappuh() : lostinsyntax() : thisisprobablybrokennow() ? //I'm lost in my own (awful) example by now.
//Not complete... or for average humans to read.

if(this != that)  //Ternary would be done by now
{
    x = this;
}
else
}
    x = this + 2;
}

A really basic rule of thumb - can you understand the whole thing as well or better on one line? Ternary is OK. Otherwise expand it.

๐ŸŒ
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.
๐ŸŒ
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.
๐ŸŒ
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.