Back to the lesson

Chaining

importance: 2

There’s a ladder object that allows to go up and down:

let ladder = {
  step: 0,
  up() {
    this.step++;
  },
  down() {
    this.step--;
  },
  showStep: function() { // shows the current step
    alert( this.step );
  }
};

Now, if we need to make several calls in sequence, can do it like this:

ladder.up();
ladder.up();
ladder.down();
ladder.showStep(); // 1

Modify the code of up and down to make the calls chainable, like this:

ladder.up().up().down().showStep(); // 1

Such approach is widely used across JavaScript libraries.

Open the sandbox with tests.

The solution is to return the object itself from every call.

let ladder = {
  step: 0,
  up() {
    this.step++;
    return this;
  },
  down() {
    this.step--;
    return this;
  },
  showStep() {
    alert( this.step );
    return this;
  }
}

ladder.up().up().down().up().down().showStep(); // 1

We also can write a single call per line. For long chains it’s more readable:

ladder
  .up()
  .up()
  .down()
  .up()
  .down()
  .showStep(); // 1

Open the solution with tests in the sandbox.