Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Javascript, is there a name for the following: variable = variable = value;

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?

like image 336
BenR Avatar asked Jun 26 '12 14:06

BenR


2 Answers

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

like image 24
Vivian River Avatar answered Oct 17 '22 01:10

Vivian River


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

like image 154
jackwanders Avatar answered Oct 17 '22 01:10

jackwanders