Chaining

What's chaining? It's when you call a function or a method, then immediately call a method of the return value.

Here's a simple example:

var printer = {  
    print: function (string) {
        console.log(string)
        return this
    }
}

printer  
    .print("hey")
    .print("what's up")
    .print("my doge?")

You know, maybe I spoke too soon about always using arrow functions. this has its uses...

Anyway, I've created an object called printer. It has one method, which does something (namely prints to the console), and then returns itself.

Since print returns an object, we can immediately call a method on that object, if that method returns an object, we can call a method on that object, and so on.

Here's a neat trick:

var print = (string) => {  
    var printer = {
        print: function (string) {
            console.log(string)
            return this
        }
    }

    return printer.print(string)
}

print("hey")  
    .print("what's up")
    .print("my doge?")
    .print("You want a challenge?")

Here's some chaining in lodash, my fave JavaScript library:

_(1)  
    .range(21)
    .filter((x) => x % 2 > 0)
    .sum()

This gives you the sum of all odd numbers between 1 and 20 (inclusive).

Breaking it down:

  • The _ function is called with a value, 1. This returns an object so we can continue the chain.
  • The range method is called on that object with 21 as the parameter. range returns another object containing an array of numbers from 1 to 20.
  • We call the filter method of that object, giving it a filtering function as a parameter. filter returns another object containing the new filtered array (only the odd numbers from the original array).
  • Lastly, we call the sum method. This just returns a number, our sum.

Once you get used to it, coding in this style becomes very easy and easy to read. Notice how it would be nothing at all to add another method call in the middle of this chain:

_(1)  
    .range(21)
    .filter((x) => x % 2 > 0)
    .map((x) => x % 5 === 0 ? 2*x : x)
    .sum()

This still works, I don't know why you'd need to get this result, but it still works. :)

Looking for a software developer?