Method Chaining and JavaScript

Sean LaFlam
4 min readOct 19, 2020

How to chain methods in JS in order to write concise and readable code.

Photo by JJ Ying on Unsplash

The Dilemma

Very often when programming, you will have the need to transform a piece of data many times in a row in order to get it to your desired final state. Each of these transformations will be carried out by a specific function/method, and will need to be done in a certain order.

When reading code, generally you read top to bottom, left to right. So if you saw a bit of code that looks like this, your instinct would be to read it like so:

myObject.method1()          <-- read this first
myObject.method2() <-- read this next
myObject.method3() <-- read this last

However, the flow of data through a series of callback functions is actually the opposite. The innermost nested function actually feeds the return value up the chain list so:

myObject.method1()                 <-- method2 passes to method1
myObject.method2() <-- method3 passes to method2
myObject.method3() <-- execute method3 first

As a result, in order to ensure you get the correct return value, you have to pretty much write the functions in reverse order when creating them. As you can imagine, the more functions you add, the messier and harder to debug it becomes. Wouldn’t it be much simpler to understand a bit of code if we could execute the functions in the order that we read them?

Want to read this story later? Save it in Journal.

Method Chaining

If you’ve ever used a fetch request in JavaScript you’ve seen something like this:

fetch('http://someurl.com/example')
.then(response => response.json())
.then(data => console.log(data))

Even if you’ve never seen this, the syntax makes it pretty easy to follow. This is called method chaining, and as you probably guessed by the use of the word ‘then’, the code executes top to bottom, exactly as it reads. Each function passes its return value to the next method in the chain. So how does this work?

Well the first thing you should understand is Javascript’s this. That in itself is a whole other massive topic, so if you want to learn more about it here is a comprehensive guide to help you out. For now, all you need to know is that when we create a new object using the syntax,

newObject = new myClass()

and call methods on that class, this refers to that object. Since it is an instance of the myClass class, it will have access to all of the methods defined for the instance, as well as access to the entire chain. Therefore if we wanted to access the method defined for the current object instance, we can use:

this.myMethod()

Now in order to chain methods together, we need to make sure that each method we define has a return value, so that we can call another method on it (this is the whole concept of chaining). Let’s see an example.

1) First we start out by creating a new class

class ChainableObject {}

2) Next, we add some methods to the class, that return this

class ChainableObject {
firstMethod(){
console.log("First Me!");
return this;
}
nextMethod(){
console.log("Then Me!");
return this;
}
}

Now, we can test our code by creating a new instance of the ChainableObject class, and calling each of our methods on it in a chain. It would look like this:

newObj = new ChainableObject()newObj.firstMethod().secondMethod()// or for even better readabilitynewObj
.firstMethod()
.secondMethod()
//Console Output
//First Me!
//Then Me!

(Test this out yourself by using ‘Inspect’ in Google Chrome)

And that is the entire process of how method chaining works! You can now apply this knowledge to more complex real-world applications using actual properties to return values.

Real-World Applications

The above code does a good job of illustrating how chaining works, but it isn’t very useful as an application. What if we wanted to use this to perform an actual function versus just logging a message to the console?

Instance Properties

In order to get a result at the end of our method chain, we need to store some values as properties within the class, as well as the return value of each function call. Let’s say we wanted to write a function that performs some simple mathematical functions, in a specific order:

This was a math problem that recently went viral on the internet through TikTok

Below I’ve created a class called Simple Calculator that performs the series of steps in the picture above.

At the bottom we define a new instance of SimpleCalculator and give it an initial value of 8. Next, we chain the divide(), add(), and multiply() methods in order to transform the data inside of it. Finally, we call .value in order to display the ending value of our .value property. Feel free to copy the code above and add your own funtionality!

More from Journal

There are many Black creators doing incredible work in Tech. This collection of resources shines a light on some of us:

--

--