Is there a name for this? Here's an example of what I'm trying to say:
var i = 0;
var j = 0;
i = j = 1;
So obviously both i
and j
are set to 1. But is there a name for this practice? Also, in terms of good coding standards, is this type of thing generally avoided? Can I also get an example or explanation of why it is/isn't good practice?
I believe that it is called "assignment chaining".
We say that assignment is "right associative". That means that
i = j = 1;
is equivalent to
i = (j = 1);
j = 1
will assign the number 1
to j
and then return the value of j (which is now 1
).
As Daniel said, it's called chained assignment. It's generally avoided, because for some values (such as objects), the line i = j = _something_
creates a reference from i
to j
. If you later change j
, then i
also changes.
var i = {};
var j = {};
i = j = {a:2};
j.a = 3; //Now, j.a === 3 AND i.a === 3
See this jsFiddle demo for an example: http://jsfiddle.net/jackwanders/a2XJw/1/
If you don't know what i
and j
are going to be, you could run into problems
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With