Home > UI/UX Development > JavaScript > What is Method Chaining in JavaScript

What is Method Chaining in JavaScript

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

  • code sample 2: with chaining

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.
This Article is TAGGED in . BOOKMARK THE permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">