Skip to content

Function chaining in JavaScript | Pattern

  • by

JavaScript Function chaining is nothing but grouping functions in one single line using dot notation. Function chaining or Method Chaining is a mechanism of calling a method on another method of the same object.

The basic syntax for function chaining in JavaScript looks like this:

object.function1().function2().function3()...

Here’s an example using function chaining with string methods:

const text = "hello, world";

const result = text
  .toUpperCase() // Convert the text to uppercase
  .replace(",", "!") // Replace the comma with an exclamation mark
  .slice(0, 5) // Get the first five characters of the modified string
  .trim(); // Remove any leading or trailing whitespace

console.log(result); // Output: "HELLO!"

In this example, we start with the text variable, which is a string. We then chain several string methods together to transform the text:

  1. toUpperCase(): Convert the entire text to uppercase.
  2. replace(",", "!"): Replace the comma with an exclamation mark.
  3. slice(0, 5): Get the first five characters of the modified string.
  4. trim(): Remove any leading or trailing whitespace.

The final result of the chaining is "HELLO!".

To achieve function chaining, each method call on the object should return the modified object (or a new object) instead of undefined. By returning the object itself, you can continue calling more methods on the returned object.

Function chaining in JavaScript

Simple example code using function chaining with regular objects. The functions such as add() and subtract() are returned and made function chaining possible thereby displaying 3 as the output.

this keyword in JavaScript refers to the current object in which it is called. Thus, when a method returns this, it simply returns an instance of the object in which it is returned.

<!DOCTYPE html>
<html>
<body>

  <script>
    var obj = function(){
      this.i = 0;
      this.add = function(i){
       this.i += i;
       return this;
     };

     this.subtract = function(i){
       this.i -= i;
       return this;
     };

     this.print = function(){
       console.log("Function chaining",this.i);
     }
   }

   var x = new obj();
   x.add(100).subtract(50).print();

 </script>

</body>
</html> 

Output:

Function chaining in JavaScript

More Example

<script>
    function Land() {
      this.area = '';
      this.status = 'for Sale';
    }

    Land.prototype.open = function() {
      this.status = 'Open for Sale';
      return this;
    }

    Land.prototype.close = function() {
      this.status = 'Not for Sale';
      return this;
    }

    Land.prototype.setParams = function(area) {
      this.area = area;
      return this;
    }

    Land.prototype.doorStatus = function() {
      console.log('The',this.area,'Land is',this.status);
      return this;
    }

    var land = new Land();
    land.setParams("500 sq ft").close().doorStatus();

</script>

Output: The 500 sq ft Land is Not for Sale

var Obj = {
  result: 0,
  addNumber: function(a, b) {
    this.result = a + b; 
    return this;
  },

  multiplyNumber: function(a) {
    this.result = this.result * a;
    return this;
  } 
};

Obj.addNumber(10, 20).multiplyNumber(10)
console.log(Obj.result)

Output: 300

Do comment if you have any doubts or suggestions on this JS concept.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *