Yes, it's valid, and it runs fine in Chrome:

var a, b, c;

a = 6;
b = 7;
c = a !== b ? (a = 1, b = 2) : (a = 2, b = 1);
console.log("a = " + a);
console.log("b = " + b);
console.log("c = " + c);

I'm not saying it's a remotely good idea in code humans are meant to read. :-) I expect jamietre is correct in the comments when he/she says it looks like the result of minification.

The comma operator is a binary operator (an operator accepting two operands). It evaluates its left-hand operand (thus causing any side-effects it has, such as assignment), throws that result away, then evalutes its right-hand operand (thus causing its side-effects if any) and takes that result as its result value. If you have multiple comma operators in a row, the overall expression is evaluated in order, left-to-right, with the final result being the value resulting from the right-most operand evaluation.

And of course, you know the conditional operator (a ternary operator — one accepting three operands) is used to pick one of two sub-expressions to evaluate, on the basis of an initial expression.

So that line is very...expressive...what with a total of seven* different expressions inside it.

So in that example, the result of the overall expression is 2 if a !== b initially, or 1 if a === b initially, with the side-effects of setting a and b.

It's the side effects that make it, in my view, a questionable choice. And of course, there's no reason to use the comma operator if the left-hand operand doesn't have side effects.


* Yes, seven of 'em packed into that overall ternary:

  • a !== b
  • the first comma expression
  • a = 1
  • b = 2
  • the second comma expression
  • a = 2
  • b = 1

Re your edit with the actual statement, that one works too:

function test(a) {
    var b = 7,
        d = 1,
        e = 2,
        f = 3,
        g = 4,
        h = 5,
        i = 6;
    
    a!==0?b<0?(h=b/a,e=h-1,f=-2*b+2*a*e,i=-2*b+2*a*h,d=2*h*a-2*b-2*a):(h=b/a,e=h+1,f=2*b-2*a*e,i=2*b-2*a*h,d=-2*h*a+2*b):d=h=e=f=i=0;
    
    console.log("a = " + a);
    console.log("b = " + b);
    console.log("d = " + d);
    console.log("e = " + e);
    console.log("f = " + f);
    console.log("g = " + g);
    console.log("h = " + h);
    console.log("i = " + i);
}

test(0);
test(1);
.as-console-wrapper {
  max-height: 100% !important;
}

But wow, I hope this is minified, because if a person wrote that, they must really have a thing against anyone who's supposed to maintain it later... ;-)

Answer from T.J. Crowder on Stack Overflow
Top answer
1 of 5
84

Yes, it's valid, and it runs fine in Chrome:

var a, b, c;

a = 6;
b = 7;
c = a !== b ? (a = 1, b = 2) : (a = 2, b = 1);
console.log("a = " + a);
console.log("b = " + b);
console.log("c = " + c);

I'm not saying it's a remotely good idea in code humans are meant to read. :-) I expect jamietre is correct in the comments when he/she says it looks like the result of minification.

The comma operator is a binary operator (an operator accepting two operands). It evaluates its left-hand operand (thus causing any side-effects it has, such as assignment), throws that result away, then evalutes its right-hand operand (thus causing its side-effects if any) and takes that result as its result value. If you have multiple comma operators in a row, the overall expression is evaluated in order, left-to-right, with the final result being the value resulting from the right-most operand evaluation.

And of course, you know the conditional operator (a ternary operator — one accepting three operands) is used to pick one of two sub-expressions to evaluate, on the basis of an initial expression.

So that line is very...expressive...what with a total of seven* different expressions inside it.

So in that example, the result of the overall expression is 2 if a !== b initially, or 1 if a === b initially, with the side-effects of setting a and b.

It's the side effects that make it, in my view, a questionable choice. And of course, there's no reason to use the comma operator if the left-hand operand doesn't have side effects.


* Yes, seven of 'em packed into that overall ternary:

  • a !== b
  • the first comma expression
  • a = 1
  • b = 2
  • the second comma expression
  • a = 2
  • b = 1

Re your edit with the actual statement, that one works too:

function test(a) {
    var b = 7,
        d = 1,
        e = 2,
        f = 3,
        g = 4,
        h = 5,
        i = 6;
    
    a!==0?b<0?(h=b/a,e=h-1,f=-2*b+2*a*e,i=-2*b+2*a*h,d=2*h*a-2*b-2*a):(h=b/a,e=h+1,f=2*b-2*a*e,i=2*b-2*a*h,d=-2*h*a+2*b):d=h=e=f=i=0;
    
    console.log("a = " + a);
    console.log("b = " + b);
    console.log("d = " + d);
    console.log("e = " + e);
    console.log("f = " + f);
    console.log("g = " + g);
    console.log("h = " + h);
    console.log("i = " + i);
}

test(0);
test(1);
.as-console-wrapper {
  max-height: 100% !important;
}

But wow, I hope this is minified, because if a person wrote that, they must really have a thing against anyone who's supposed to maintain it later... ;-)

2 of 5
44

Yes:

a=1;
b=2;

a!==b ? (a=1, b=2) : (a=2, b=1)

console.log(a);     // 1
console.log(b);     // 2

and:

a=1;
b=2;

a===b ? (a=1, b=2) : (a=2, b=1)

console.log(a);     // 2
console.log(b);     // 1

As you can analyze, changing the equality operator reacts correctly to our test if you look at the results.

🌐
Reddit
reddit.com › r/react › nested ternary operators. how bad are they?
r/react on Reddit: Nested ternary operators. How bad are they?
January 26, 2024 -

So I saw an article recently that was talking about minimizing the use of ternary operators where possible and reflecting on my own use of them especially in JSX, I have a few questions...

Before I get decided to post my questions, I checked React subs and most discussions on this are a couple years old at least and I thought perhaps views have changed.

Questions:

  1. Is the main issue with using nested ternary operators readability?

I have found myself using ternary operators more and more lately and I even have my own way of formatting them to make them more readable. For example,

            info.type === "playlist"
            ?   info.creationDate
                ?   <div className="lt-info-stats">
                        <span className="text pure">Created on {info.creationDate}</span>
                    </div>
                :   null
            :   info.type === "artist"
                ?   <div className="lt-info-stats">
                        <span className="text pure">{info.genre}</span>
                    </div>
                :   <div className="lt-info-stats">
                        <span className="text pure">{info.releaseDate}</span>
                        <span className="cdot" style={{ fontWeight: "bold", margin: "1px" }}>·</span>
                        <span className="text pure">{info.genre}</span>
                    </div>

When written like this, I can visually see the blocks and tell them apart and it looks a lot like how an if/else might look.

nested ternary operator formatting

2. What is the preferred formatting of ternary operators in general and what do you think should be done to make them more readable?

3. How do people feel about nested ternary operators today? How big of a nono is it to have them in code (if it is a nono)?

I would love you know peoples thoughts on ternary operators in React in general as well.

Thanks for your attention!

🌐
W3Schools
w3schools.com › react › react_es6_ternary.asp
React ES6 Ternary Operator
React Compiler React Quiz React Exercises React Syllabus React Study Plan React Server React Interview Prep React Certificate ... The ternary operator is a simplified conditional operator like if / else.
🌐
Educative
educative.io › answers › how-to-use-the-ternary-operator-in-react
How to use the ternary operator in React
To use a ternary operator for multiple conditions in React JS, you can nest the ternary operators. Each nested ternary operator handles a different condition, allowing you to render different elements based on each case.
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-use-multiple-ternary-operators-in-a-single-statement-in-javascript
How to use multiple ternary operators in a single statement in ...
September 19, 2024 - In the above syntax, we have tested 2 conditions in a single statement using the ternary operator. In the syntax, if condition1 is incorrect then Expression3 will be executed else if condition1 is correct then the output depends on condition2. If condition 2 is correct, then the output is Expression1. If it is incorrect, then the output is Expression2. In this example, we are checking two conditions and using nested ternary operators to return the corresponding expression based on the conditions:
Find elsewhere
🌐
DhiWise
dhiwise.com › post › how-to-use-the-ternary-operator-in-react-for-cleaner-code
Simplify React Code: Mastering the Ternary operator in React
August 9, 2024 - Inline use: Unlike if-else statements, ternary operators can be used directly within expressions, including return statements and JSX in React. Immutability: Ternary operators work well with const variables in JavaScript, allowing you to maintain the immutability of your variables. While the ternary operator is a powerful tool, there are situations where traditional if-else statements might be more suitable: Complex conditions: If your condition has multiple branches, using if-else statements can make your code easier to understand.
🌐
DEV Community
dev.to › samba_code › nested-ternary-statements-in-react-jsx-35kp
Nested Ternary statements in React JSX - DEV Community
June 18, 2019 - Which I think in general everyone can get behind as a rule. It's not readable code, even when split over multiple lines with indentations, and should be broken out into if statements. However, this is a very common pattern in React where we can use ternary statements to do conditional rendering in a component.
🌐
Devcamp
utahedu.devcamp.com › dissecting-react-js › guide › multi-line-ternary-operators-react-showing-hiding-dropzone-components
Guide to Multi Line Ternary Operators in React for Showing and Hiding the Dropzone Components
So that is a ternary operator, we first check for a condition or a set of conditions, like you're gonna see, and then if it's true, we want to perform one task, then we give a : and then whatever comes after the : we want to have that be the second task and you can split this up into multiple lines, and that's what we are going to do.
🌐
Stack Overflow
stackoverflow.com › questions › 50613864 › react-multiple-conditions-inside-ternary-operator
reactjs - React multiple conditions inside ternary operator? - Stack Overflow
Nevermind I figured it out I didn't know you could have 2 conditions with logical operators inside ternary operators. Here is what I did to fix it. {this.state.userId == row.reply_user_id && this.state.isLoggedin == true ?
🌐
Codecademy
codecademy.com › forum_questions › 50a735d192bf860b2000077c
Ternary operator more than one condition | Codecademy
I understand the ternary operator for the conditional statement is as shown below: var Name = "Mike"; if (Name === "Mike" { ...
🌐
Robin Wieruch
robinwieruch.de › conditional-rendering-react
React Conditional Rendering
You can use the boolean to decide ... ... The parentheses () around both implicit return statements in the ternary operator enable you to return a single or multiple HTML elements or React components from there....
🌐
React
legacy.reactjs.org › docs › conditional-rendering.html
Conditional Rendering – React
class LoginControl extends React.Component { constructor(props) { super(props); this.handleLoginClick = this.handleLoginClick.bind(this); this.handleLogoutClick = this.handleLogoutClick.bind(this); this.state = {isLoggedIn: false}; } handleLoginClick() { this.setState({isLoggedIn: true}); } handleLogoutClick() { this.setState({isLoggedIn: false}); } render() { const isLoggedIn = this.state.isLoggedIn; let button; if (isLoggedIn) { button = <LogoutButton onClick={this.handleLogoutClick} />; } else { button = <LoginButton onClick={this.handleLoginClick} />; } return ( <div> <Greeting isLoggedIn=
🌐
Medium
medium.com › @JavaScript-World › ternary-operator-in-react-js-ed488675c2c
Ternary Operator in React.js. In JavaScript, the ternary operator… | by JavaScript-World | Medium
May 23, 2023 - <h1>React is fun!</h1> : <h1>React ... tag based on the value of this.state.isReactFun. As we progress, ternary operators can be nested for multiple conditions....