Multiple assignments inside an if statement

Why can't I do this:

 var fooElement, barElements;
 if (fooElement = document.getElementById ('foo') && barElements = fooElement.getElementsByTagName ('bar') && barElements [0] && barElements [0] .onclick)
 {
     console.log (barElements [0] .onclick);
 }

This will not work either:

 var foo, bar;
 if (foo = true && bar = true)
 {
     console.log ('yay');
 }
+8
javascript variable-assignment if-statement
source share
2 answers

Try this (this should give you the key):

var foo, bar; if((foo = true) && (bar = true)) { console.log('yay'); } 
+10
source share

Check operator priority, use

 if((foo = true) && (bar = true)) { alert(foo); } 

UPD: do not forget that the following code does not set bar to true, because && is a Short Circuit operator

 if((foo = false) && (bar = true)) { alert(foo); } 

Example

+2
source share

All Articles