Beautiful JavaScript: Easily Create Chainable (Cascading) Methods for Expressiveness

»aug. 13 2013 29

(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.

Bov Academy

of Programming and Futuristic Engineering

Invest in Your Future: Become a Frontend/Fullstack Engineer

Within 6–8 Months, Earn > the Avg. New CS Graduate Earns

30% Discount for the May Session

By the founder of JavaScriptIsSexy

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.

  • Receive Updates

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", lastName: "MalCom", email: "test@test.com", id: 102},
    {firstName: "Peter", lastName: "breCht", email: "test2@test2.com", id: 103},
    {firstName: "RoHan", lastName: "sahu", email: "test3@test3.com", id: 104}
];


// A quick utility function that does what it says:
function titleCaseName(str) {
    return str.replace(/\w\S*/g, function (txt) {
        return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
    });
}


// Our object with the chainable methods
var userController = {

    currentUser: "",

    findUser: function (userEmail) {
        var arrayLength = usersData.length, i;
        for (i = arrayLength - 1; i >= 0; i--) {
            if (usersData[i].email === userEmail) {
                this.currentUser = usersData[i];
                break;
            }
        }
        return this;
    },

    formatName: function () {
        if (this.currentUser) {
            this.currentUser.fullName = titleCaseName(this.currentUser.firstName) + " " + titleCaseName(this.currentUser.lastName);
        }
        return this;

    },

    createLayout: function () {
        if (this.currentUser) {
            this.currentUser.viewData = "<h2>Member: " + this.currentUser.fullName + "</h2>"
            + "<p>ID: " + this.currentUser.id + "</p>" + "<p>Email: " + this.currentUser.email + "</p>";
        }
        return this;
    },

    displayUser: function () {
        if (!this.currentUser) return;

        $(".members-wrapper").append(this.currentUser.viewData);

    }
};

With our chainable methods defined, we can now execute our expressive code like this (just like it is done in jQuery):
Continue Reading

12 Simple (Yet Powerful) JavaScript Tips

»feb. 20 2013 38

(For Badass JavaScript Development)

NOTICE: I have written only 2 of the 12 tips so far, but I plan to post all 12 Powerful Tips eventually.

I provide you with 12 simple, yet powerful, JavaScript tips and detailed explanation of each. These are techniques that all JavaScript programmers can use now; you needn’t be an advanced JavaScript developer to benefit from these tips. After you read all of the detailed explanations of how each technique works and when to use it, you will have become a more enlightened JavaScript developer, if you aren’t already one.

Indeed, notable JavaScript masters and enlightened JavaScript developers have been using many of these techniques to write powerful, efficient JavaScript. And in a bit, you will, too.

Bov Academy

of Programming and Futuristic Engineering

Invest in Your Future: Become a Frontend/Fullstack Engineer

Within 6–8 Months, Earn > the Avg. New CS Graduate Earns

30% Discount for the May Session

By the founder of JavaScriptIsSexy

  1. Powerful JavaScript Idiomatic Expressions With && and ||

    You see these idiomatic expressions in JavaScript frameworks and libraries. Let’s start off with a couple of basic examples:

    • Receive Updates


    Example 1: Basic “short circuting” with || (Logical OR)
    To set default values, instead of this: Continue Reading