feat(curriculum): Add interactive examples to Method chaining lesson (#63403)

This commit is contained in:
Giftea ☕
2025-10-31 13:29:34 -07:00
committed by GitHub
parent 0ef0992514
commit 0e6dd568fb
@@ -5,12 +5,14 @@ challengeType: 19
dashedName: what-is-method-chaining-and-how-does-it-work
---
# --description--
# --interactive--
Method chaining is a programming technique that allows you to call multiple methods on the same object in a single line of code. This technique can make your code more readable and concise, especially when performing a series of operations on the same object.
Let's look at an example using different string methods:
:::interactive_editor
```js
const result = " Hello, World! "
.trim()
@@ -20,12 +22,16 @@ const result = " Hello, World! "
console.log(result); // "hello, JavaScript!"
```
:::
In this example, we start with a string and perform three operations in sequence: trim whitespace, convert to lowercase, and replace the string `world` with `JavaScript`. Each method returns a new string, which becomes the target of the next method call.
Method chaining can significantly improve code readability when working with complex operations.
For instance, consider this example using the `filter`, `map` and `reduce` methods:
:::interactive_editor
```js
const transactions = [
{ amount: 100, type: "credit" },
@@ -43,6 +49,8 @@ const totalCreditWithBonus = transactions
console.log(totalCreditWithBonus); // 357.5
```
:::
In this example, we have an array of transactions where each object has an amount and a credit card or cash type.
We first filter through the transactions and create a new array of just credit card transactions. Then, we chain the `map` method to the filtered result and for each transaction amount, we multiply it by `1.1` which represents a `10%` bonus.