The expression inside the following function is evaluated right to left
function foo(){
var a = b = c;
}
so it's like it was typed this way
var a = (b = 0)
However, when methods are chained together, they are read left to right. The methods in this object...
var obj = {
value: 1,
increment: function () {
this.value += 1;
return this;
},
add: function (v) {
this.value += v;
return this;
},
shout: function () {
alert(this.value);
}
};
can be called like this, evaluated left to right
obj.increment().add(3).shout(); // 5
// as opposed to calling them one by one
obj.increment();
obj.add(3);
obj.shout(); // 5
So, I think I know when to read left to right and right to left, but is there a rule that I need to know which I don't know?
Rule is called 'operator associativity' and is, along with operator precedence, a property of every operator (arithmetic, member access, be it unary or binary, etc.) in most of languages. Associativity is usually defined by language specs, and can often be found in books, tutorials, cheatsheets, and so on. One of first google results for javascript is here: http://www.javascriptkit.com/jsref/precedence_operators.shtml
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With