This post was most recently updated on August 5th, 2024
Hello everyone, in this post we will discuss about following points on Method Chaining
- What is Method Chaining?
- Pros and Cons of Method Chaining
What is method chaining?
Method chaining is technique that allows to write several methods on jQuery selection in sequence in a single code statement. jQuery relies heavily on chaining. This makes it easy to call several methods on the same selection. It also makes code more clear and prevents executing the same selection several times (hence improving performance).
Consider following code sample
- code sample 1: without chaining
12345$(document).ready(function(){$('#userContent').addClass('hi');$('#userContent').css('color', 'green');$('#userContent').fadeOut('slow');});
- code sample 2: with chaining
12345$(document).ready(function(){$('#userContent').addClass('hi').css('color', 'green').fadeOut('slow');});
Both these code samples does the same thing. The code sample 2 uses chaining and it is faster and shorter in code where as code sample 1 has to search the entire DOM to find the element and after that it executes the function on it.
Pros and Cons of Method Chaining
- Pros of method chaining
- Performance wise method chaining is far better.
- It makes your code short and easy to manage.
- Selector is only evaluated once for multiple operations.
- The chain starts from left to right. So left most will be called first and so on.
- Cons of method chaining
- Writing too many consecutive chained methods on one line can compromise code readability if it extends to make a very long line of code.