简体   繁体   中英

Javascript simplified if-statement

I'm scratching my head trying to understand this very simplified if statement. When searching for the answer, all I find is answers related to ternary operators.

Anyway. Why is it that the first case below works, while the latter throws an ReferenceError ? Just trying to understand how things work.

 true && alert("test") 

 var x; true && x = 10; 

This has to do with operator precedence . As the && operation is computed before the = , your second example would end up making no sense : (true && x) = 10;

For your second case to work, add parenthesis this way :

 var x; true && (x = 10); 

Javascript seems to give higher precedence to && than to the assignment operator. The second line you gave is parsed as:

(true && x) = 10;

If you add parenthesis around the assignment, I think you will see the behavior that you were expecting:

true && (x = 10);  // Sets x to 10 and the whole expression evaluates to 10.

And just in case you needed a pointer as to why && can be used as an if-statement, the phrase "short-circuit evaluation" might help.

It'a Operator precedence .

As you can see && has higher priority than =

So true && x = 10; is actually (true && x) = 10; which is clearly wrong. You can only assign value to variables, and (true && x) is either false or the value of x .

The result of alert() is undefined. So first example could be retyped as:

 var x; // x is now 'undefined' true && x; // true and undefined is undefined 

The second example is about operators priorities. Runtime evaluate expression as (true && x) = 10;

 var x; true && (x = 10); // result will be 10 

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