Skip to content

Chaining method calls in JavaScript

New Course Coming Soon:

Get Really Good at Git

In JavaScript sometimes we can chain method calls, like this:

car.start().drive()

It’s pretty convenient to do so.

Instead of writing

car.start()
car.drive()

we can simplify in a one-liner.

This is possible if each method returns the object itself. In other words, the implementation must be something like this:

const car = {
  start: function() {
    console.log('start')
    return this
  },
  drive: function() {
    console.log('drive')
    return this
  }
}

It’s important to note that you can’t use arrow functions, because this in an arrow function used as object method is not bound to the object instance.

I like to use arrow functions all the time, and this is one of the cases where you can’t.

Chained method calls are great when you are not returning a set of values from the method, otherwise you obviously need to assign a method call to a variable, and chaining is not possible:

const result = car.start()
if (result) {
  car.drive()
}
Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching May 21, 2024. Join the waiting list!
→ Get my JavaScript Beginner's Handbook
→ Read my JavaScript Tutorials on The Valley of Code
→ Read my TypeScript Tutorial on The Valley of Code

Here is how can I help you: