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?
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?
Share Improve this question asked Nov 23, 2012 at 23:56 BrainLikeADullPencilBrainLikeADullPencil 11.7k24 gold badges82 silver badges138 bronze badges1 Answer
Reset to default 8Rule 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./jsref/precedence_operators.shtml