en.javascript.info icon indicating copy to clipboard operation
en.javascript.info copied to clipboard

Error in ladder method chaining example (ladder.up().up().down().showStep().down().showStep())

Open alihasnainh3techs opened this issue 3 months ago • 2 comments

In the JavaScript.info tutorial, the following example is incorrect:

ladder.up().up().down().showStep().down().showStep(); // shows 1 then 0

It actually throws this error in the console: Uncaught TypeError: Cannot read properties of undefined (reading 'up')

Reason: Each method (up, down, showStep) does not return any value, so they implicitly return undefined. After the first call, ladder.up() returns undefined, and chaining another .up() results in undefined.up().

Fix: Return the object itself (this) from each method to enable chaining.

Corrected Example:

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

ladder.up().up().down().showStep().down().showStep(); // works as expected

alihasnainh3techs avatar Oct 21 '25 05:10 alihasnainh3techs

It's not an example, it's a task: "Modify the code..." You succeeded.

Image

joaquinelio avatar Oct 21 '25 23:10 joaquinelio

ohh I see

alihasnainh3techs avatar Oct 22 '25 11:10 alihasnainh3techs