What is function chaining in JavaScript

Function chaining in javascript

Function chaining is also called cascading.

Method chaining is a technique that can be used to simplify code in scenarios that involve calling multiple functions on the same object consecutively.

Without function chaining Jquery Example

 $('#myDive').removeClass('display-none'); 
#('#myDive').addClass('display-block'); 

With function chaining Jquery Example

  $('#myDiv').removeClass('display-none').addClass('display-block'); 

User Details example without function chaining

 var User = function (){ 
this.name = 'xyz'; 
this.age = 30; 
this.gender = 'male'; 
};  

User.prototype.setName = function(name) {   
this.name = name; 
};  

User.prototype.setAge = function(age) {   
this.age = age; 
};  

User.prototype.setGender = function(gender) {   
this.gender = gender; 
};  

User.prototype.print = function() {   
console.log('My Name is '+ this.name + '. I am a '+ this.gender +'. My age is ' +this.age); 
}  

var obj = new User();  
obj.setName('Anil Kapoor'); 
obj.setAge(27); 
obj.setGender('male');  
obj.print(); 

Implementing Function Chaining

 var User = function (){ 
this.name = 'xyz'; 
this.age = 30; 
this.gender = 'male'; 
};  

User.prototype.setName = function(name) {   
this.name = name;   
return this; 
};  

User.prototype.setAge = function(age) {   
this.age = age;   
return this; 
};  

User.prototype.setGender = function(gender) {   
this.gender = gender;   
return this; 
};  

User.prototype.print = function() {   
console.log('My Name is '+ this.name + '. I am a '+ this.gender +'. My age is ' +this.age); 
}  

var obj = new User();  
obj.setName('Anil Kapoor').setAge(27).setGender('male').print(); 

How To Use Server-Sent Events …

How To Use Server-Sent Events in Node.js to Build a Realtime App. Server-Sent Events (SSE) is a technology based on HTTP. On the client-side, it provides an API called EventSource (part of the HTML5 standard) that allows us to connect to the server a …

read more

How To Use node-cron to Run Sc …

How To Use node-cron to Run Scheduled Jobs in Node.js . cron provides a way to repeat a task at a specific time interval. There may be repetitive tasks such as logging and performing backups that need to occur on a daily or weekly basis.One method fo …

read more