Skip to content

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

@alihasnainh3techs

Description

@alihasnainh3techs

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions