Chaining methods together in JavaScript is quit common. If you've used jQuery, you've likely performed this technique. It's sometimes called the "Builder Pattern".
It's a technique that is used to simplify code where multiple functions are applied to an object one after another.
// Instead of applying the functions one per line... arr = [1,2,3,4]; arr1 = arr.reverse(); arr2 = arr1.concat([5,6]); arr3 = arr2.map(Math.sqrt); // ...they can be chained together into a one-liner console.log([1,2,3,4].reverse().concat([5,6]).map(Math.sqrt)); // parentheses may be used to illustrate console.log(((([1,2,3,4]).reverse()).concat([5,6])).map(Math.sqrt) );
This only works when the functions are methods of the object being worked on. If you created your own function that, for example, takes two arrays and returns an array with the two arrays zipped together, you must declare it as a member of the Array.prototype
object. Take a look at the following code snippet:
Array.prototype.zip = function(arr2) { // ... }
This would allow us to the following:
arr.zip([11,12,13,14).map(function(n){return n*2}); // Output: 2, 22, 4, 24, 6, 26, 8, 28