5

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?

BenR
  • 2,791
  • 3
  • 26
  • 36

3 Answers3

6

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

jackwanders
  • 15,612
  • 3
  • 40
  • 40
  • Thank you, this was exactly what I was looking for. I could have sworn that I tried this once before and it skewed what I was trying to do, and this explains it. Thank you again! – BenR Jun 26 '12 at 16:52
1

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).

Vivian River
  • 31,198
  • 62
  • 198
  • 313
0

Sometimes it's referred to as "chained assignment" and sometimes as "multiple variable assignment". Also, you might want to look at the answers to this question.

Community
  • 1
  • 1
iCanLearn
  • 336
  • 1
  • 4
  • 17