Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

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

Open
@alihasnainh3techs

Description

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

        AltStyle によって変換されたページ (->オリジナル) /