Voice of a Developer: JavaScript Chaining - Part Sixteen

Introduction

 
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  
  3. while working with strings: 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 the 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.     this.name = '';  
  3. }  
  4. games.prototype.getName = function() {  
  5.     this.name = 'Age of Empire';  
  6.     return this;  
  7. }  
  8. games.prototype.setName = function(n) {  
  9.         this.name = n;  
  10.     }  
  11.     //now execute it    
  12. var g = new games();  
  13. g.getName().setName('Angry Birds');  
  14. console.log(g.name); 
We’ve created a 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 the examine the 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.