The assignment expressions are always evaluated from right-to-left. So what the above expression actually does is, assign the value
10 to the variable
d, then assign the value of
c and so on. Finally all the variables will get the value
10. This kind of “short-hand” code will allows you to get rid of the repetitive code; especially when you want to initialise multiple variables with an initial value.
And what’s the catch here ?
Well, in simple words: “the scope“ . To understand that, let’s move the same expression inside a function. Like this:
If you expect all of these variables are having a scope local to the function
foo, then you’re wrong. What happens here is, the var statement is only applicable to the variable
a. And all the other variables are considered with out the
var statement, hence will be the global. Try executing foo method, you would see:
Yes, that’s the catch ! So avoid multiple left-hand assignments inside any functions. If you’re writing this in global level ( you’re assuming all of your variables to go in global scope ), then this is not at all an issue. So better watch out next time before you do this.
If you’re not convinced and still want to do left-hand assignments, then the right way of doing it is like this: