1

I have the following code:

var $scope, modelValue;
modelValue = $scope.model = {};

Can anyone please explain what this double assignment mean in javascript?

Why does one need the second assignment?

1
  • Why ? to save you from writing it twice. Commented Feb 23, 2014 at 10:08

2 Answers 2

4

This line modelValue = $scope.model = {}; is exactly like writing this:

$scope.model = {};
modelValue = $scope.model;

When writing an expression: variable = expression, the expression is evaluated before the assignment, so this statement is evaluated from right to left:

variable = (variable = expression) // inner expression

I found this docs: http://msdn.microsoft.com/en-us/library/1w2h1k9x(v=vs.94).aspx:

The = operator behaves like other operators, so expressions that contain it have a value. This means that you can chain assignment operators as follows: j = k = l = 0. In this case j, k, and l equal zero.

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

1 Comment

Interesting... Can you please confirm that the $scope.model = {}; instruction is evaluated first?
1

With this statement you have a direct reference to the empty object via modelValue and set the model under the $scope namespace/object to the same object. If you need to dereference to the model it should be quicker via the direct reference. And to shorten things up (referencing the same object with two variables) you make a double assignment.

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.