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?

1

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

1 Comment

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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.