Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

right to left evaluation, left to right chain methods

Tags:

javascript

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?

like image 381
BrainLikeADullPencil Avatar asked Feb 18 '23 09:02

BrainLikeADullPencil


1 Answers

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

like image 180
Maciek Avatar answered Mar 05 '23 06:03

Maciek