(Part of the “12 Powerful JavaScript Tips” Series)
Prerequisites:
— Understand JavaScript’s “this” With Ease
— JavaScript Objects in Detail
Chaining Methods, also known as Cascading, refers to repeatedly calling one method after another on an object, in one continuous line of code. This technique abounds in jQuery and other JavaScript libraries and it is even common in some JavaScript native methods.
[sc:mongodb-book]Writing code like this:
$("#wrapper").fadeOut().html("Welcome, Sir").fadeIn();or this:
str.replace("k", "R").toUpperCase().substr(0,4);is not just pleasurable and convenient but also succinct and intelligible. It allows us to read code like a sentence, flowing gracefully across the page. It also frees us from the monotonous, blocky structures we usually construct.
We will spend the next 20 minutes learning to create expressive code using this cascading technique. To use cascading, we have to return this (the object we want subsequent methods to operate on) in each method. Let’s quickly learn the details and get back to eating, or watching YouTube videos, or reading Hacker News, or working and browsing, or working and focusing.
Let’s create all of our “chainable” code within an object, along with a local data store. Note that in a real-world app we will likely store the data in a database, but here we are just saving it in a variable.
// The data store: var usersData = [ {firstName: "tommy",