5

I'm sure this thing is duplicated somewhere but I don't know what to search.

So, I've been looking through a Node.JS Application and found this code and wondered what it does. I have tried searching but I don't know what to search so I was hoping someone would it explain it to me.

init = refresh = function () {
    // code here..
};

I understand 1 equals, but why 2? does it make some sort of alias so that function can be run with both init and refresh?

2
  • Variable assignment works like that, yes. (a = b sets a to b and evaluates to b; it resolves right to left.) Commented Sep 21, 2013 at 21:41
  • Basically what it's doing is assigning function(){...} to both init and refresh. Commented Sep 21, 2013 at 21:57

3 Answers 3

5

= resolves the right hand side and then assigns the result to the left hand side.

The result of doing this is the same as the result assigned.

So that assigns the function to both init and refresh

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

1 Comment

Thanks for that, I'm just reading code (as its a new language to me) at the moment and that was something new to me..
4

Quentin did a very good job telling you what it is doing. I just wanted to chime in to give an example where you might use this:

Say for instance you have an object:

var obj = {
    init: function() {
        var x = this.x = [1,2,3];
    }
};

What this allows you to do is reference your x variable two different ways (either through x or this.x).

Now why would you do this? Well two major reasons.

  1. It is faster to access x rather than this.x (but you still need to access it elsewhere)
  2. It produces easier to read code when having to read/write to x lots of times in one function.

This is just another reason why you would use it.

But in most cases it is just aliases, such as: forEach -> each

Comments

3

Here's an explanation using operator associativity and precedence.

So, looking at an operator precedence description from Mozilla, when an expression includes multiple operators of the same precedence, as in

a OP b OP c

, then you check whether that level of precedence uses right-to-left or left-to-right associativity.

a = b = c

The assignment operator in JavaScript is the only operator on its level of precedence.

It has right-to-left associativity

So in a = b = c, b = c is evaluated first, assigning the value of c to b.

Then the expression becomes a = b.

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.