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(); 

Explain the concept of Web Workers in HTML-5

Web Workers in HTML5 introduce a way to run scripts in the background, separate from the main browser thread. They enable multitasking by allowing tasks to be offloaded to a different thread, preventing them from blocking the main user interface (UI) …

read more

How can you embed audio and video in HTML-5

In HTML5, you can embed audio and video content using the <audio> and <video> elements, respectively. The <audio> element is used to embed audio content in a web page. Here's an example:

read more