Back to Freecodecamp

What Is Method Chaining, and How Does It Work?

curriculum/challenges/english/blocks/lecture-working-with-higher-order-functions-and-callbacks/673362cbb475e21eab726506.md

latest4.2 KB
Original Source

--interactive--

Method chaining is a technique where you call several methods one after another. You can use method chaining on many types of values in JavaScript including strings, arrays, and objects. Even though strings are primitive values, JavaScript temporarily wraps them in a String object when you use a string method.

Let's look at an example using different string methods:

:::interactive_editor

js
const result = "  Hello, World!  "
  .trim()
  .toLowerCase()
  .replace("world", "JavaScript");

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" },
  { amount: 20, type: "cash" },
  { amount: 150, type: "credit" },
  { amount: 50, type: "cash" },
  { amount: 75, type: "credit" }
];

const totalCreditWithBonus = transactions
  .filter((transaction) => transaction.type === "credit")
  .map((transaction) => transaction.amount * 1.1)
  .reduce((sum, amount) => sum + amount, 0);

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.

Then, we take that result and chain the reduce method to add up each of the amounts which results in 357.5.

While method chaining can make code more concise and readable, it's important to use it judiciously.

Very long chains can become difficult to debug, as it's not immediately clear which step in the chain might be causing an issue. It's often a good practice to break very long chains into multiple steps for better clarity and easier debugging.

--questions--

--text--

What will be the output of the following code?

js
let str = "  HELLO world  ";
let result = str.trim().toLowerCase().split(' ');
console.log(result);

--answers--

["HELLO", "world"]

--feedback--

Consider the effect of each method in the chain: trim(), toLowerCase(), and split().


["hello", "world"]


"hello world"

--feedback--

Consider the effect of each method in the chain: trim(), toLowerCase(), and split().


[" HELLO", "world "]

--feedback--

Consider the effect of each method in the chain: trim(), toLowerCase(), and split().

--video-solution--

2

--text--

In the context of method chaining, what should a method typically return to allow further chaining?

--answers--

undefined

--feedback--

Think about what allows the next method in the chain to be called immediately after the current one.


null

--feedback--

Think about what allows the next method in the chain to be called immediately after the current one.


The object itself (this).


A new object.

--feedback--

Think about what allows the next method in the chain to be called immediately after the current one.

--video-solution--

3

--text--

What will be the result of the following code?

js
let obj = {
    value: 1,
    increment: function() {
        this.value++;
        return this;
    },
    double: function() {
        this.value *= 2;
        return this;
    },
    getValue: function() {
        return this.value;
    }
};

let result = obj.increment().double().increment().getValue();
console.log(result);

--answers--

2

--feedback--

Follow the chain of method calls and their effects on the value property.


3

--feedback--

Follow the chain of method calls and their effects on the value property.


4

--feedback--

Follow the chain of method calls and their effects on the value property.


5

--video-solution--

4