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

August 13 Last Year

(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, is the technique of repeatedly calling different methods (or the same method) on an object in one continuous line of code. This technique is popular in jQuery and other JavaScript libraries, and it is even inherent in JavaScript’s native methods like the common String methods.

The expressiveness of writing this:

$("#wrapper").fadeOut().html("Welcome, Sir").fadeIn();

Or this:

str.replace("k", "R").toUpperCase().substr(0,4); 

is just so lovely that we can’t resist making our own methods facilitate cascading.

We will buoyantly spend the next 20 minutes creating the same kind of loveliness in our own code, for it will be regrettable if we don’t. We will learn that this technique is easy and effortless because it is rather straightforward to implement chainable methods in JavaScript. We only have to return this (the object we want subsequent methods to operate on) in each method. Let’s learn this baby quickly and get back to what we were doing.

Let’s create all of our chainable code within an object, along with a local data store that we will use. Note that in a real-world app, we will likely store the data in a database, but here we are just saving it 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 Last Year

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.

Functions are objects in JavaScript, as we should know well by now, and as objects, functions have methods, including the powerful Apply, Call, and Bind methods. Apply and Call are nearly identical and they are used frequently in JavaScript for borrowing methods and explicitly setting the this value. We also use Apply for variable-arity functions. We use Bind for setting the this value in methods, in addition for Function Currying.

We will discuss all the scenarios in which these 3 methods are most often used in JavaScript. While Apply and Call are part of ECMAScript 3 (available on IE 6, 7, 8, and modern browsers), ECMAScript 5 (available only on 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

16 JavaScript Concepts JavaScript Professionals Must Know Well

July 9 Last Year

(Essential JavaScript Concepts for Modern JavaScript Development )

If you are already or plan on becoming a JavaScript Professional, there are some JavaScript concepts and JavaScript-related web-development technologies that you must know well as a modern JavaScript developer. If you know these 16 concepts below very well, you have the skill necessary to build world-class modern JavaScript web applications and you are set for the near future—0-3 years.

I will expound on each of these sixteen concepts, and I am hopeful all of us will have become better JavaScript programmers by the time we get through all of them. I have completed most of the 16 concepts with just a few more to go, so keep reading and learning. And sign up on the homepage for the newsletter to get the latest updates.

I trust you have learned JavaScript properly or you already know JavaScript enough to build a simple, pure JavaScript web application. While the 16 concepts below are neither complex nor for advanced JS developers only, you will get the most benefit from the linked articles, if you already know at least some basic JavaScript.

These are the sixteen concepts that every modern JavaScript developer must know very well:

  1. JavaScript Objects in Detail
  2. JavaScript Prototype in Plain, Detailed Language
  3. JavaScript Variable Scope and Hoisting Explained
  4. Understand JavaScript Closures With Ease
  5. Understand JavaScript Callback (Higher-Order) Functions
  6. Understand JavaScript’s “this” With Clarity, and Master It
  7. JavaScript’s Apply, Call, and Bind Methods are Essential
  8. Learn HTML5, CSS3, and Responsive WebSite Design
  9. Object Oriented JavaScript (OOP in JavaScript)
  10. Learn Node.js Completely and With Confidence Or Learn Meteor.js and Embrace the Future (coming soon)
  11. Continue Reading

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

July 5 Last Year

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

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

The this keyword in JavaScript is notorious for confusing JavaScript developers. This article aims to elucidate this in its entirety. The goal: by the time we make it through this article, this will be one part of JavaScript we will never have to worry about again, and we should understand how to use this completely and in every scenario, including the ticklish situations when this goes rogue.

this is used similar to the way the pronoun is used 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: “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 will abandon us. Yes, they will. In a similar aesthetic manner, we use the this keyword as a shortcut in JavaScript.

    var person = {
    firstName   :"Penelope",
    lastName    :"Barrymore",
fullName:function () {
// See how we use "this" here just like we used "he" in the example sentence?
console.log(this.firstName + " " + this.lastName);

// Well, we could have also written:
console.log(person.firstName + " " + person.lastName);
}
}

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 fistName property from the person global variable, and this could lead to difficult-to-debug errors. So, using the “this” keyword is not only for the aesthetics, but it actually makes our code more unambiguous, just as the pronoun “he” made our sentence clear 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. this not only refers to the object but it actually contains the value of the object. 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”, if you will allow me)—more on context later.

JavaScript’s this Keyword Basics

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

this 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 strict mode is being used, this holds the value of undefined in global functions and in anonymous functions that are not bound to any objects.
Continue Reading

Learn HTML5, CSS3, and Responsive WebSite Design in One Go

May 6 Last Year

(You will also learn HTML5 Boilerplate, Modernizr, and Twitter Bootstrap 3.0 responsive website layout)

Prerequisite: Familiarity with basic HTML and CSS
Duration: 2 – 3 days (about 18 hours)

We have learned quite a bit of JavaScript, but we must take a break from JavaScript briefly and learn HTML5 and CSS3, because we need both, along with JavaScript of course, to build modern web applications and websites.

Both CSS3 and HTML5 are just about fully supported in all modern browsers, and we there are techniques in place to patch old browsers that lack support. So there is no disadvantage to using CSS3 and HTML5 today. The opposite is true, however: there are many painful, frustrating disadvantages with forgoing HTML5 and CSS3.

You may already “know” a bit of HTML5 and a touch of CSS3 (or perhaps you probably know enough old-school HTML and CSS), and with this knowledge, you might have thought you needn’t learn HTML5 and CSS3 fully.

The crux of the matter is that after you complete this course, you will make faster, more user friendly, highly adaptive websites and web applications. And you will learn a number of other very exciting modern web development techniques.

Responsive Web Design is becoming increasingly essential (we are probably a few months away from responsive being mandatory) with the ubiquity of the myriad screen sizes available today. As a result, modern web developers are expected to understand and implement responsive web designs.

What You Will Learn?

  • HTML5 Core (HTML5 semantics, video, and audio; and later, Advanced HTML5 APIs)
  • Responsive Web Design (create fluid, responsive layouts from scratch and from static, pixel based layouts; responsive images, icons, and videos; and more)
  • Tools and Strategies for Designing the user interface and static comps for responsive websites
  • HTML5 Boilerplate, Modernizr, and Initializr
  • Twitter Bootstrap 3.0 Responsive Layout and Best Practices

Continue Reading

OOP In JavaScript: What You NEED to Know

March 19 Last Year

(Object Oriented JavaScript: Only Two Techniques Matter)

Prerequisite:
JavaScript Objects in Detail
JavaScript Prototype

The main principle with Object Oriented Programming (OOP) is the use of Classes (Functions in JavaScript) to create objects, and that objects are implemented in a manner that allows them to adopt Inheritance, Polymorphism, and Encapsulation. We are only concerned with Inheritance and Encapsulation, since only these are applicable for OOP in JavaScript. Essentially, objects can encapsulate functionalities and inherit methods and properties.

The rest of this article will focus on using objects in JavaScript in an object oriented manner—with inheritance and encapsulation—to easily reuse code in our applications and abstract functionalities away into specialized objects. We will focus only on the best two techniques [1] for implementing OOP in JavaScript. Continue Reading

Understand JavaScript Callback Functions and Use Them

March 4 Last Year

(Learn JavaScript Higher-order Functions—Callback Functions)

In JavaScript, functions are first-class objects, which means functions can be used in a first-class manner like objects, since they are in fact objects themselves: They can be “stored in variables, passed as arguments to functions, created within functions, and returned from functions” [1].

Because functions are first-class objects, we can use callback functions in JavaScript. In the rest of this article we will learn everything about callback functions. Callback functions are probably the most widely used functional programming technique in JavaScript, and they are literally in just about every piece of JavaScript and jQuery code, yet they are a mystery to many JavaScript developers. You will know how to use them after reading this article.

Callback functions are derived from a programming paradigm called functional programming. At a simple and fundamental level, functional programming is the use of functions as arguments. Functional programming was—and still is, though to a much lesser extent today—seen as an esoteric technique of specially trained, master programmers.

Fortunately, the techniques of functional programming have been elucidated so mere mortals like you and I can understand and use them with ease. One of the chief techniques in functional programming is that of callback functions. As you will read shortly, implementing callback functions is as easy as passing regular variables as arguments to functions. This technique is so easy that I wonder why it is usually covered only in advanced JavaScript topics.
Continue Reading

Learn Intermediate and Advanced JavaScript

February 25 Last Year

(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

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

If you are new to JavaScript and you are an experienced programmer in another langauge such as Java, Python, ActionScript, Rails, and PHP, it is important that you learn JavaScript properly. JavaScript has many idiosyncracies and uncommon concepts that you must know well before you follow this Intermediate to Advanced JavaScript course.
Continue Reading

How to Learn JavaScript Properly

February 24 Last Year

Learn JavaScript Properly (For NON-JavaScript Programmers and First-time Programmers)

Duration: 6 to 8 weeks.
Prerequisite: Completed at least some high school (no programming experience necessary).
Continue course below.

New New Update (January 7, 2014):
A new study group has just started on Reddit:
January 2014, “Learn JavaScript” Study Group on Reddit

Note that there is also a Reddit-based study group, amongst others noted in the comments below. But these other groups have all started months ago.


This course outline gives you a structured and instructive roadmap on how to learn JavaScript properly and thoroughly, from absolute beginner to attainment.

You do want to learn JavaScript; it is why you are here, and you have made a wise decision, for if you want to develop modern websites and web applications (including an internet startup), you need to know JavaScript. And while there are more than enough online resources to teach you JavaScript, finding the most efficient and beneficial method to learn the “language of the web” is not easy and could be frustrating.

It is worth noting that unlike just a couple of years ago when you needed to know a true server-side language (such as PHP, Rails, Java, Python, or Perl) to develop scalable, dynamic, database-driven web applications, today you can do as much and more with JavaScript alone.
Continue Reading

12 Simple (Yet Powerful) JavaScript Tips

February 20 Last Year

(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 by April 14. This will be a must-read post once all the powerful tips are ready. ;)

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.

  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:

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