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