What is Method Chaining in Javascript 🤔

write better code with method chaining in javascript

Ankit Aabad
2 min readSep 21, 2021

Instead of getting theoretical let’s write a program to understand method chaining. We will write a program to find if two words are anagrams. Anagrams are words that are formed by rearranging the letters of a word.

For eg MARY can be rearranged to form ARMY so MARY and ARMY are anagrams. our task is to write a function to find if two strings are anagrams or not. We will write a suboptimal solution to solve this problem. The idea is to understand method chaining and not to solve this problem in the best possible way.

Method Chaining

There are two functions in our code.

  1. sort_string
  2. is_anagram

sort_string takes a string and returns a sorted string. let’s see it in action.

sort string
sort_string(‘mAry ‘)
sort string
sort_string(‘ armY ‘)

so basically sort_string takes a string as input and applies a chain of methods to it. Every method returns an object and on that object, we again call another method. for eg split method on a string returns an array and we call the sort method of the array on it in a chain which again returns an array and we call the join method on it which returns a string.

For both ‘mAry ’ and ‘ armY ’, our sort_string function returns ‘amry’ and our is_anagram function just compares the result of sort_string for both strings and returns true if both are the same.

In method chaining, every method returns an object which allows us to invoke another method on it in a chain.

Benefits of Method Chaining:

  • Fewer lines of code
  • No need to think about variable names to store intermediate results.
  • It looks elegant. 😄

This is my first post on medium, I hope you enjoyed reading this post as much as I enjoyed writing it. 🤗

--

--

Ankit Aabad

A software engineer who 🥰 to read and write.