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

A Once-in-a-Lifetime Opportunity

Train to Become an Exceptional and Successful Developer

While Building Real-World Projects You Can Benefit from for Years

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

JavaScript’s Apply, Call, and Bind Methods are Essential for JavaScript Professionals

»july. 10 2013 103

Prerequisite:
Understand JavaScript’s “this” With Ease, and Master It.
JavaScript Objects
Understand JavaScript Closures
(This is an intermediate to advanced topic)

Duration: About 40 minutes.

Bov Academy

of Programming and Futuristic Engineering

A Once-in-a-Lifetime Opportunity

Train to Become an Exceptional and Successful Developer

While Building Real-World Projects You Can Benefit from for Years

By the founder of JavaScriptIsSexy

Functions are objects in JavaScript, as you should know by now, if you have read any of the prerequisite articles. And as objects, functions have methods, including the powerful Apply, Call, and Bind methods. On the one hand, Apply and Call are nearly identical and are frequently used in JavaScript for borrowing methods and for setting the this value explicitly. We also use Apply for variable-arity functions; you will learn more about this in a bit.

  • Receive Updates

On the other hand, we use Bind for setting the this value in methods and for currying functions.

We will discuss every scenario in which we use these three methods in JavaScript. While Apply and Call come with ECMAScript 3 (available on IE 6, 7, 8, and modern browsers), ECMAScript 5 (available on only modern browsers) added the Bind method. These 3 Function methods are workhorses and sometimes you absolutely need one of them. Let’s begin with the Bind method.
Continue Reading

Understand JavaScript’s “this” With Clarity, and Master It

»july. 5 2013 172

(Also learn all the scenarios when this is most misunderstood.)

Prerequisite: A bit of JavaScript.
Duration: about 40 minutes.

The this keyword in JavaScript confuses new and seasoned JavaScript developers alike. This article aims to elucidate this in its entirety. By the time we make it through this article, this will be one part of JavaScript we never have to worry about again. We will understand how to use this correctly in every scenario, including the ticklish situations where it usually proves most elusive.

Bov Academy

of Programming and Futuristic Engineering

A Once-in-a-Lifetime Opportunity

Train to Become an Exceptional and Successful Developer

While Building Real-World Projects You Can Benefit from for Years

By the founder of JavaScriptIsSexy

We use this similar to the way we use pronouns in natural languages like English and French. We write, “John is running fast because he is trying to catch the train.”

Note the use of the pronoun “he.” We could have written this: “John is running fast because John is trying to catch the train.” We don’t reuse “John” in this manner, for if we do, our family, friends, and colleagues would abandon us. Yes, they would. Well, maybe not your family, but those of us with fair-weather friends and colleagues. In a similar graceful manner, in JavaScript, we use the this keyword as a shortcut, a referent; it refers to an object; that is, the subject in context, or the subject of the executing code. Consider this example:

    var person = {
    firstName: "Penelope",
    lastName: "Barrymore",
    fullName: function () {
        ​// Notice we use "this" just as we used "he" in the example sentence earlier?:
        console.log(this.firstName + " " + this.lastName);
    ​// We could have also written this:​
        console.log(person.firstName + " " + person.lastName);
    }
}

  • Receive Updates


If we use person.firstName and person.lastName, as in the last example, our code becomes ambiguous. Consider that there could be another global variable (that we might or might not be aware of) with the name “person.” Then, references to person.firstName could attempt to access the firstName property from the person global variable, and this could lead to difficult-to-debug errors. So we use the “this” keyword not only for aesthetics (i.e., as a referent), but also for precision; its use actually makes our code more unambiguous, just as the pronoun “he” made our sentence more clear. It tells us that we are referring to the specific John at the beginning of the sentence.

Just like the pronoun “he” is used to refer to the antecedent (antecedent is the noun that a pronoun refers to), the this keyword is similarly used to refer to an object that the function (where this is used) is bound to. The this keyword not only refers to the object but it also contains the value of the object. Just like the pronoun, this can be thought of as a shortcut (or a reasonably unambiguous substitute) to refer back to the object in context (the “antecedent object”). We will learn more about context later.

JavaScript’s this Keyword Basics

First, know that all functions in JavaScript have properties, just as objects have properties. And when a function executes, it gets the this property—a variable with the value of the object that invokes the function where this is used.

The this reference ALWAYS refers to (and holds the value of) an object—a singular object—and it is usually used inside a function or a method, although it can be used outside a function in the global scope. Note that when we use strict mode, this holds the value of undefined in global functions and in anonymous functions that are not bound to any object.
Continue Reading

Learn Intermediate and Advanced JavaScript

»feb. 25 2013 26

(Learn Intermediate and Advanced JavaScript Concepts and Techniques in 2 Weeks)

Prerequisite:
You have completed this course: Learn JavaScript Properly (For NON-JavaScript programmers and First-time Programmers)

Or you already know the following JavaScript concepts well:
— Simple Data Types, Reference Types, Operators, and Objects (in Detail)
— Variable Scope and Hoisting, Expressions, Statements, and JSON
— DOM, The Window Object, JavaScript Events, and Handling Errors
— Functions, Function Properties, Function Expression, and AJAX
— Basic Regular Expressions and Modules

Duration:
2 Weeks

Bov Academy

of Programming and Futuristic Engineering

A Once-in-a-Lifetime Opportunity

Train to Become an Exceptional and Successful Developer

While Building Real-World Projects You Can Benefit from for Years

By the founder of JavaScriptIsSexy


I submit to you an instructive course on intermediate and advanced JavaScript. The skills you will learn in this course of study will free you from the constrains of using the limited JS techniques you have been using to develop JS applications, and they will give you new insights and new techniques—a Jedi’s temperament and stature—to program JS applications with ease, efficiency, and precision.

If you are new to JavaScript and you are an experienced programmer in another language such as Java, Python, ActionScript, Rails, and PHP, it is important that you learn JavaScript properly. JavaScript has many idiosyncrasies and uncommon concepts that you must know well before you follow this Intermediate to Advanced JavaScript course.
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

A Once-in-a-Lifetime Opportunity

Train to Become an Exceptional and Successful Developer

While Building Real-World Projects You Can Benefit from for Years

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