Method chaining is a coding technique in JavaScript that allows you to call multiple methods on an object in a single continuous sequence. Each method in the chain returns the object itself, which enables you to call another method on the returned object. This results in a more concise and readable code structure.
Here's an example to illustrate method chaining in JavaScript:
class Calculator {
constructor(value = 0) {
this.value = value;
}
add(num) {
this.value += num;
return this; // Return the object for chaining
}
subtract(num) {
this.value -= num;
return this; // Return the object for chaining
}
multiply(num) {
this.value *= num;
return this; // Return the object for chaining
}
divide(num) {
if (num !== 0) {
this.value /= num;
} else {
console.log("Error: Division by zero.");
}
return this; // Return the object for chaining
}
getValue() {
return this.value;
}
}
// Using method chaining to perform multiple operations
const result = new Calculator(10)
.add(5)
.subtract(3)
.multiply(2)
.divide(4)
.getValue();
console.log(result); // Outputs: 5
In this example:
We have a Calculator class with methods for basic arithmetic operations:
add, subtract, multiply, and
divide.
Each method returns this, which refers to the current
Calculator object, allowing us to chain methods together.
We create a Calculator object with an initial value of 10 and then perform a series of operations using method chaining.
The final result is obtained using the getValue method.
Method chaining makes the code more concise and readable because it allows you to perform a sequence of operations on an object without repeatedly referencing the object itself. This technique is commonly used in JavaScript libraries and frameworks to create expressive and fluent APIs, making it easier to work with complex objects and functions.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Method chaining is a coding technique in JavaScript that allows you to call multiple methods on an object in a single continuous sequence. Each method in the chain returns the object itself, which enables you to call another method on the returned object. This results in a more concise and readable code structure.
Here's an example to illustrate method chaining in JavaScript:
In this example:
Method chaining makes the code more concise and readable because it allows you to perform a sequence of operations on an object without repeatedly referencing the object itself. This technique is commonly used in JavaScript libraries and frameworks to create expressive and fluent APIs, making it easier to work with complex objects and functions.