javascript - What is the outcome of: var myvar1 = myvar2 = myvar3? - Stack Overflow

admin2025-04-15  0

I have seen in some nodejs scripts variables/objects being used like this:

var myvar1 = myvar2 = myvar3;

Why is this used and what does it mean?

I have seen in some nodejs scripts variables/objects being used like this:

var myvar1 = myvar2 = myvar3;

Why is this used and what does it mean?

Share Improve this question edited Sep 22, 2011 at 14:23 c69 21.6k8 gold badges55 silver badges83 bronze badges asked Sep 22, 2011 at 14:21 wilsonpagewilsonpage 17.6k23 gold badges105 silver badges150 bronze badges 2
  • 2 Lots of enthusiastic answers, but only a couple mentioning the scope correctly. – Chris Morgan Commented Sep 22, 2011 at 14:28
  • possible duplicate of Multiple left-hand assignment with JavaScript – Chris Morgan Commented Sep 22, 2011 at 14:33
Add a ment  | 

6 Answers 6

Reset to default 4

It will evaluate to:

var myvar1 = myvar2 = myvar3;
var myvar1 = myvar3;          // 'myvar2' has been set to 'myvar3' by now
myvar3;                       // 'myvar1' has been set to 'myvar3' by now

It will first assign myvar3 to myvar2 (without var, so possibly implicit global, watch out for that).

Then it will assign myvar3's value to myvar1, because the set value is returned.

The result is again returned, which won't do anything further - in the final line nothing happens with myvar3's value.

So in the end they have all the same value.

This sets myvar2 to myvar3, and sets myvar1 to myvar2.

I assume myvar3 and myvar2 have been declared before this line. If not, myvar2 would be a global (as there's no var), and if myvar3 wasn't defined, this would give an error.

This expands to:

myvar2 = myvar3; // Notice there's no "var" here
var myvar1 = myvar2;

If:

var myvar3 = 5;

var myvar1 = myvar2 = myvar3;

Then they are all = 5

myvar1 and myvar2 both get the name of myvar3. the first expression to evaluate is myvar2 = myvar3. This assigns myvar3 to myvar2. The result of this operation is the assigned value , and this is then assigned to myvar1.

This will assign the variables myvar1 and myvar2 to the value of myvar3. Why they do this is unknown to me, but my best guess is they want the two vars to be the same value of myvar3.

as already explained, the statement results in all variables having the value myvar3.

I like to add: using statements like that you have to beware of scope, demonstrated by:

function foo(){
  var c = 1;
  var a = b = c;
  console.log(a,b,c); //=> 1 1 1
  c = 2;
  console.log(a,b,c); //=> 1 1 2
}
console.log(b); //=> 1! [b] is now a variable in the global scope 

And of assigning non primitive values (so, references to objects)

function foo(){
  var c = {};
  var a = b = c;
  c.bar = 2;
  console.log(a.bar,b.bar,c.bar); 
       //=> 1 1 1 (a, b and c point to the same object)
}
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1744687245a261213.html

最新回复(0)