Javascript Cascade Design Pattern

Alex Z
Tiny Code Lessons
Published in
2 min readSep 25, 2015

The Javascript cascade design pattern is a way to create a chaining pattern for methods of our own objects.

The simple example is this:

var string = 'string cheese';  
string.split('').reverse().join();

We are able to cascade functions on the string because each time we call a function on the string, the function returns an object containing properties and methods inherited from their prototypal object. The way this works is generally obscured from you as a developer, but it is a fundamental concept of Javascript. Everything is an object with a prototype that it inherits from, and that’s what allows us to do cool things like cascading.

This concept is really powerful when we extend it to objects of our own making. This (very simple) example illustrates that it is possible to create our own number class and add functions to it that alter the object and return the object, rather than returning a value. This allows us to chain methods, just like the pros.

function number(value){  
this.value= value;
this.plus= function(sum){
this.value += sum;
return this;
};

this.return= function(){
return this.value;
};
return this;
}

number.prototype.minus = function(min){
this.value -= min;
return this;
}

new number(5).plus(1).minus(2).return(); // 4

This is constructor function syntax for creating cascading functions. Every function that we add to the number constructor returns this, so that the resulting object will have all of the functions of the entire object. I like this as an example because you can actively add methods to the prototypal object that you are working with (number.prototype).

function init(number){  
var Key = Math.rand()*100;
n = {value: number,
plus: function(sum){
n.value += sum;
return n;
},
return: function(){
return n.value;
}
}
return n;
}


init(1).plus(1).plus(2).return(); // 4

This is more functional syntax for creating cascading functions. The advantage of this syntax is that it is scoped privately. If we wanted to build a function that applies an encryption to the number value but keeps the actual encryption key private, this would allow us to do so.

And that’s cascading in Javascript. There are tons of places to go from here — obviously we can use this syntax and apply it to more complex situations, like chaining functions for querying and manipulating user data in the browser. We can also actually create custom methods that build off the prototypes that already exist in JS.

Originally published at blog.alexzitowolf.com on August 17, 2015.

--

--

Alex Z
Tiny Code Lessons

Software Developer + Product Manager. Interested in Travel, Culture, Economics and the Internet. Join Medium: https://tinycode.medium.com/membership