Method Chaining in Javascript

By | September 3, 2017

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

This chain is just a single expression. It’s easy enough to break this chain down and make each of the calls into separate expressions, but then it would obviously not be method chaining anymore. In below example, you can see how to use method chaining in jQuery.

// Without Method Chaining

var $div = $('#my-div');         // assign to var
$div.css('background', 'blue');  // set background color
$div.height(100);                // set height
$div.fadeIn(200);                // show element

// With Method Chaining

$('#my-div').css('background', 'blue').height(100).fadeIn(200);

As you can see, using method chaining can tidy up code quite a bit, however some developers dislike the visual style of method chaining and choose not to use it.


Like it? Share it