0

I am learning Node.js. On the book I am using there is a line that I am not sure I know exactly how it works and was looking for confirmation.

The line is:

var user = req.user = users[req.params.name];

I did some research on Google and the way I believe this works is:

As a first step will copy the content of users[request.params.name] into req.user then as a second step will copy the content of req.user into user. In the end user == users[req.params.name];

Can you please confirm that I am getting this right or, if not, explain how this line works?

thanks

1
  • You really couldn't figure this out just by running it? Commented Nov 20, 2013 at 22:18

1 Answer 1

3

That's essentially it. What you have there is a compound assignment. The result of an assignment expression is the value being assigned, and so that value can be the right-hand side of another assignment expression.

But there's actually something else that happens before any of that: The variable user gets defined in the current context. Here's a detailled order of operation:

  1. Upon entry to the context, the variable user is defined with the value undefined. This happens before any step-by-step code in the context happens.

  2. When the execution cursor reaches that code in the step-by-step execution of code, then:

    1. The property params is looked up on the variable req.

    2. The property name is looked up on the result of req.params.

    3. The property with the name defined by that value (the value of req.params.name) is retrieved from the object (presumably) referenced by the users variable.

    4. The resulting value is assigned to the user property on req.

    5. The same value is assigned to the user variable.

(I skipped a couple of bookkeeping steps to avoid overdoing the predantry.)

It's important to note that between steps 2.4 and 2.5 above, the value of req.user is not read from the req.user property. The value is determined in 2.3 and then used in 2.4 and again in 2.5. That is, a = b = c; is not the same as b = c; a = b;. The difference is that in the latter, the value is retrieved from b in the second assignment; in the former, it isn't, it's just reused from the b = c part. Now, when it's a simple property, that distinction doesn't particularly matter, but it does if you're using property accessor functions (either the non-standard kind from Mozilla's earlier variant of JavaScript, or the newly-standard kind from ECMAScript5). Live Example of the difference | Source

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

1 Comment

This is great and, honestly, much more than I was expecting. Appreciate your detailed response.

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.