Junior
How to call a method in a chain of calls?
sobes.tech AI
Answer from AI
Using a dot (.) between method calls or object properties. Each method call or property access returns an object, on which you can then call the next method or access the next property.
// Example of method chaining
" abc ".trim().toUpperCase().split(" ");
/*
1. " abc ".trim() -> "abc"
2. "abc".toUpperCase() -> "ABC"
3. "ABC".split(" ") -> ["ABC"]
*/
// Example of property access chain
const user = {
address: {
city: "Moscow"
}
};
user.address.city; // "Moscow"
// Example using optional chaining (?.)
// Allows safe access to nested object properties,
// preventing errors if any intermediate property is null or undefined.
user.address?.street; // undefined, no error
const anotherUser = {};
anotherUser.address?.city; // undefined, no error
When designing your methods to support chaining, each method should return this (a reference to the current object), except for the last method in the chain, which can return the final result.
class Builder {
constructor() {
this.value = "";
}
addText(text) {
this.value += text;
return this; // Return this
}
addNumber(number) {
this.value += number;
return this; // Return this
}
build() {
return this.value; // Return the final result
}
}
const result = new Builder().addText("Hello").addNumber(123).build();
console.log(result); // "Hello123"