First of all, a ternary expression is not a replacement for an if/else construct - it's an equivalent to an if/else construct that returns a value. That is, an if/else clause is code, a ternary expression is an expression, meaning that it returns a value.

This means several things:

  • use ternary expressions only when you have a variable on the left side of the = that is to be assigned the return value
  • only use ternary expressions when the returned value is to be one of two values (or use nested expressions if that is fitting)
  • each part of the expression (after ? and after : ) should return a value without side effects (the expression x = true returns true as all expressions return the last value, but it also changes x without x having any effect on the returned value)

In short - the 'correct' use of a ternary expression is

var resultofexpression = conditionasboolean ? truepart: falsepart;

Instead of your example condition ? x=true : null ;, where you use a ternary expression to set the value of x, you can use this:

 condition && (x = true);

This is still an expression and might therefore not pass validation, so an even better approach would be

 void(condition && x = true);

The last one will pass validation.

But then again, if the expected value is a boolean, just use the result of the condition expression itself

var x = (condition); // var x = (foo == "bar");

UPDATE

In relation to your sample, this is probably more appropriate:

defaults.slideshowWidth = defaults.slideshowWidth || obj.find('img').width()+'px';
Answer from Sean Kinsey on Stack Overflow
Top answer
1 of 13
363

First of all, a ternary expression is not a replacement for an if/else construct - it's an equivalent to an if/else construct that returns a value. That is, an if/else clause is code, a ternary expression is an expression, meaning that it returns a value.

This means several things:

  • use ternary expressions only when you have a variable on the left side of the = that is to be assigned the return value
  • only use ternary expressions when the returned value is to be one of two values (or use nested expressions if that is fitting)
  • each part of the expression (after ? and after : ) should return a value without side effects (the expression x = true returns true as all expressions return the last value, but it also changes x without x having any effect on the returned value)

In short - the 'correct' use of a ternary expression is

var resultofexpression = conditionasboolean ? truepart: falsepart;

Instead of your example condition ? x=true : null ;, where you use a ternary expression to set the value of x, you can use this:

 condition && (x = true);

This is still an expression and might therefore not pass validation, so an even better approach would be

 void(condition && x = true);

The last one will pass validation.

But then again, if the expected value is a boolean, just use the result of the condition expression itself

var x = (condition); // var x = (foo == "bar");

UPDATE

In relation to your sample, this is probably more appropriate:

defaults.slideshowWidth = defaults.slideshowWidth || obj.find('img').width()+'px';
2 of 13
32

No, it needs three operands. That's why they're called ternary operators.

However, for what you have as your example, you can do this:

if(condition) x = true;

Although it's safer to have braces if you need to add more than one statement in the future:

if(condition) { x = true; }

Edit: Now that you mention the actual code in which your question applies to:

if(!defaults.slideshowWidth)
    { defaults.slideshowWidth = obj.find('img').width()+'px'; }
🌐
Reddit
reddit.com › r/learnjavascript › ternary without else
r/learnjavascript on Reddit: Ternary without else
July 3, 2023 -

I have scoured StackOverflow regarding this issue and the suggested solution seems to be to use the && operator instead of a ternary statement like so condition && (x = true); , however this doesn't work when I use it in my code:

let a = false

b = a && 3

console.log(b)

This logs false instead of undefined which is what I expected since a is false.

🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Operators › Conditional_operator
Conditional (ternary) operator - JavaScript | MDN
The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark (?), then an expression to execute if the condition is truthy followed by a colon (:), and finally the expression to execute if the condition is falsy.
🌐
DEV Community
dev.to › dailydevtips1 › javascript-if-shorthand-without-the-else-13ch
JavaScript if shorthand without the else - DEV Community
August 1, 2022 - However, sometimes we might want to execute or set something if a specific condition is met. Let's look at the following example. ... This piece of code should alert the user if the our_value condition is truthy. There is no else involved.
🌐
SitePoint
sitepoint.com › javascript
Ternary operator - JavaScript - SitePoint Forums | Web Development & Design Community
August 22, 2010 - The question is a theoretical one regarding the JavaScript syntax for ternary operator. Now, in conclusion I think that the following syntaxes works but isn’t a good solution: ... There is difference of semantics in regards to ternary operators. It’s better when they are used to just to assign values. If you want to run a different set of statements or functions, staying with the if/else structure is a better choice.
🌐
Mblogs
mbloging.com › post › learn-how-to-use-the-javascript-ternary-operator-effectively-without-else
Master JavaScript Ternary Operator: Usage Without Else | Mbloging
Single-Line Conditionals: Best ... statements. ... The ternary operator is a shorthand for conditional evaluations, replacing traditional if-else statements with a more concise format....
🌐
Daily Dev Tips
daily-dev-tips.com › posts › javascript-if-shorthand-without-the-else
JavaScript if shorthand without the else
August 1, 2022 - However, sometimes we might want to execute or set something if a specific condition is met. Let’s look at the following example. ... This piece of code should alert the user if the our_value condition is truthy. There is no else involved.
🌐
Built In
builtin.com › software-engineering-perspectives › ternary-operator-js
Ternary Operator in JavaScript Explained | Built In
It is written as “?:” and takes three operands; a logical condition, a value to return if true, and a value to return if false. But it’s common knowledge among developers that if/else statements with lots of conditions can get messy.
Find elsewhere
🌐
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. ... The conditional (ternary) operator is the only JavaScript operator that takes three operands.
🌐
freeCodeCamp
freecodecamp.org › news › the-ternary-operator-in-javascript
JavaScript Ternary Operator – Syntax and Example Use Case
January 6, 2023 - You cannot use the operator without assigning the returned value to a variable: const result = condition ? trueExpression : falseExpression · The returned value depends on the evaluation of the condition expression.
🌐
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 - In this tutorial, we’ll explore ... operator (also known as the conditional operator) can be used to perform inline condition checking instead of using if...else statements....
🌐
Refine
refine.dev › home › blog › tutorials › how to use the javascript ternary operator
How to Use the JavaScript Ternary Operator | Refine
October 8, 2024 - I wanted to share a few quick insights about the JavaScript Ternary Operator that might be useful: ... Sometimes we use ternary operators to simplify code and short-circuit logic. It’s a quick way to check a condition and return something based on it without writing an if/else block.
🌐
Programiz
programiz.com › javascript › ternary-operator
JavaScript Ternary Operator (with Examples)
In JavaScript, a ternary operator can be used to replace certain types of if..else statements.
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › javascript-ternary-operator
JavaScript Ternary Operator - GeeksforGeeks
The ternary operator can also be used inside functions to simplify conditional logic. It helps make functions more concise by replacing if...else statements with a single-line expression.
Published   June 24, 2019
🌐
Jrsinclair
jrsinclair.com › articles › 2021 › rethinking-the-javascript-ternary-operator
Rethinking the JavaScript ternary operator
It doesn’t take a lot of effort to translate that into prose. If someCondition evaluates as true then call the function takeAction with no arguments. Else, call the function someOtherAction with no arguments. That’s not a big leap. The ternary operator though is made-up of cryptic symbols.
🌐
Scaler
scaler.com › home › topics › javascript › javascript ternary operator
JavaScript Ternary Operator - Scaler Topics
February 19, 2024 - JavaScript's Ternary Operator (?:) condenses conditional logic with three operands, offering an alternative to if-else statements. Enhancing code readability and simplicity, it enables concise representation of conditional blocks within expressions.
🌐
JavaScript Tutorial
javascripttutorial.net › home › javascript tutorial › javascript ternary operator
JavaScript Ternary Operator
November 15, 2024 - In this example, the returned value of the ternary operator is the last value in the comma-separated list. ... If the locked is 1, then the canChange variable is set to false, otherwise, it is set to true. In this case, you can simplify it by using a Boolean expression as follows: let locked = 1; let canChange = locked != 1;Code language: JavaScript (javascript)