Voice of a Developer: JavaScript Chaining - Part Sixteen

JavaScript is a language of the Web. This series of articles will talk about my observations learned during my decade of software development experience with JavaScript.

Before moving further let us look at the previous articles of the series:

Chaining

Chaining

This technique got / retrieved popularity from jQuery. We write series of statements one after the other like a chain,

ex,

  1. $("#h1").text("Change text").css("color""red");  
  2. Another example of chaining while working with strings:  
  3. var s="hello";  
  4. s.substring(0,4).replace('h','H'); //Hell  
The Chaining Method is also known as Cascading, because it repeatedly calls one method on an object forming a chain/continuous line of code.

Chaining methods

Ques: What is returned if there is no return statement in method?

Ans: undefined

Ques: How is chaining implemented?

Ans: When a method returns this; the entire object is returned & it is passed to next method and it is called chaining. Example,
  1. var games = function()  
  2. {  
  3.     this.name = '';  
  4. }  
  5. games.prototype.getName = function()  
  6. {  
  7.     this.name = 'Age of Empire';  
  8.     return this;  
  9. }  
  10. games.prototype.setName = function(n)   
  11.     {  
  12.         this.name = n;  
  13.     }  
  14.     //now execute it  
  15. var g = new games();  
  16. g.getName().setName('Angry Birds');  
  17. console.log(g.name);  
We’ve created getName method which returns this and implemented chaining.

Advantages 
  • Code is more maintainable, simple, lean
  • It is easy to read chaining code

Simplify code after chaining

Use case: Let usthe examine traditional way to program things. We have a problem to sort string below:

Approach 1

  1. var vehicles = "Bike|Car|Jeep|Bicycle";  
  2. vehicles = vehicles.split( "|" );  
  3. vehicles = vehicles.sort();  
  4. vehicles = vehicles.join( "," );  
  5. console.log(vehicles);  
Output: Bicycle, Bike, Car, Jeep

Approach 2:
  1. var vehicles = "Bike|Car|Jeep|Bicycle";  
  2. vehicles = vehicles.split('|').sort().join(',');  
  3. console.log(vehicles);  
Output: Bicycle, Bike, Car, Jeep

Please share your feedback / comments.

Up Next
    Ebook Download
    View all
    Learn
    View all