JavaScript: Cascading Methods (Method Chaining)

One extremely useful programming pattern that can be implemented in JavaScript is that of ‘cascading methods’ also known as ‘method chaining’. Method chaining is accomplished in JS by simply returning the object that was just operated on as the result of the method call. By doing this, a developer can call a method and then instantly call another method on the same object without referencing the object or capturing the result of the previous method call.

This is possible due to the fact that the result of a method is returned directly after the method call itself and is therefore used as the object of interest for the following (chained) method call (see example code below).

'use strict';

// Cascading/Chaining Methods
//  1. Return 'this' instead of 'undefined' at the end of your Methods
//  2. This allows the focused Object to be returned and additional Methods to be called on it

var person = {
    first_name: 'First name not provided',
    middle_initial: 'initial not provided',
    last_name: 'Last name not provided',
    age: 'Age not provided',

    change_first_name: function(new_name){
        this.first_name = new_name;
        return this; // Return the current object

    change_last_name: function(new_name){
        this.last_name = new_name;
        return this; // Return the current object

    change_middle_initial: function(new_initial){
        this.middle_initial = new_initial;
        return this; // Return the current object

// Call each of the Object's methods one right after the other

console.log('First Name: ' + person.first_name);
console.log('Middle Initial: ' + person.middle_initial);
console.log('Last Name: ' + person.last_name);

Published by

Tim Clark

Experienced Business Owner, Chief Information Officer, Vice President, Chief Software Architect, Application Architect, Project Manager, Software Developer, Senior Web Developer, Graphic Designer & 3D Modeler, University Instructor, University Program Chair, Academic Director. Specialties: Ruby, Ruby on Rails, JavaScript, JQuery, AJAX, Node.js, React.js, Angular.js, MySQL, PostgreSQL, MongoDB, SQL Server, Responsive Design, HTML5, XHTML, CSS3, C#,, Project Management, System Design/Architecture, Web Design, Web Development, Adobe CS6 (Photoshop, Illustrator)

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s