Multiple variable assignments on one line

Since each programming language is different, and my experience with Javascript is at a basic level, I would like to know how several variable assignments are evaluated on the same line

Example:

a = b = c = d = 5; 

Will such an instruction assign 5 each of the 4 variables a , b , c and d ?

Thanks.

+4
source share
4 answers

The short answer is yes, this operator assigns 5 each of the 4 variables a , b , c and d . But, contrary to what has been said, it does not assign 5 d , and then a value from d to c , but it assigns the same values ​​to each variable, starting from the right side. To be more clear, your statement:

 var a, b, c, d; a = b = c = d = 5; 

This is equivalent to:

 var d = 5; var c = 5; var b = 5; var a = 5; 

Not :

 var d = 5; var c = d; var b = c; var a = b; 

This is a subtle but important difference: in the first case, JavaScript simply sets the value for all variables. In the second case, JavaScript set the value for all variables , but also got the value of three variables (the value of a not assigned anywhere).

Simple code that will show that:

 // `this` is the global object if you run this code in the global scope. // In the browsers the global object is `window`. Object.defineProperties(this, { "a": { get: function() { console.log("get a"); }, set: function(value) { console.log("set a"); } }, "b": { get: function() { console.log("get b"); }, set: function(value) { console.log("set b"); } }, "c": { get: function() { console.log("get c"); }, set: function(value) { console.log("set c"); } }, "d": { get: function() { console.log("get d"); }, set: function(value) { console.log("set d"); } } }); b = c = d = 5; a = b; 

On the console, you should:

 set d set c set b get b set a 

As you can see for the operator b = c = d = 5 JS, only set the variable and call both set and get on b , because the operator is a = b .

This difference is very important because if you define some getter for your property and you are not aware of this behavior, you will get an unexpected error using several variable assignments.

+16
source

For the most part, yes, but consider the following scenario:

 Object.defineProperty(this, "b", { value : 6, writable : false }); var a, c, d; a = b = c = d = 5; console.log(a); // 5 console.log(b); // 6 console.log(c); // 5 console.log(d); // 5 
+5
source

The answer is yes.

 a=b=c=d=e=f=g=h=4; // all get to be 4 a=b=c=d=e=f=g=h={ p1:"1", p2:"2" }; // same object for all a.p3 = "3"; console.log((a==b && b==c && c==d && d==e), f); // condition is true, f is now // { // p1:"1", // p2:"2", // p3:"3" // } 
+2
source

You only need to try to answer this question: Yes .

The reason it works is because the assignment accepts everything on the right side of the equal sign and assigns this value to the variable on the left side.

So 5 assigned to d ; then the value of d assigned to c , etc.

0
source

All Articles