简体   繁体   中英

What is the reason behind var a = (expression1, expression2) in javascript?

Looking through some JS code I have found something like this:

var a, b;
if (  
  (a = someFunction1(), b = someFunction2() )
){
   ...
}

I never found anything like this previously and I do not understand the reason for doing something like this. Therefore I am curious: is the person who has done this out of his mind or am I just not capable to understand his idea.

When I try to check what construct like (expression1, expression2) does, I see that it always returns the value of the second expression:

(5, 6)   // 6
('strange', 'things')    // 'things'
(4, undefined)     // undefined

So if I would be the one writing this code, I would do something like this:

var a = someFunction1(),
    b = someFunction2();

if (b){ ... }

Am I correct in my reasoning?

When I try to check what construct like (expression1, expression2) does, I see that it always returns the value of the second expression

Yes. Even without trying out, this is what the comma operator does.

Am I correct in my reasoning?

Yes. Your code does exactly the same thing, but is more readable.

You are correct, that is essentially if(b) . The readability of the first version is terrible and does not save on space so it would make no sense for it to be minified like that.

Assigning variables inside of conditional statements is bad practice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM