0% found this document useful (0 votes)
4 views

JavaScript is Super Sexy _ JavaScript is Sexy

The document celebrates JavaScript as a versatile and appealing programming language, highlighting its attractive frontend and robust backend capabilities. It emphasizes JavaScript's accessibility for both beginners and experienced developers, and discusses the importance of learning frameworks like Backbone.js for building modern web applications. Additionally, it outlines a roadmap for mastering Backbone.js and encourages continuous learning in the JavaScript ecosystem.

Uploaded by

Hem Lok
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

JavaScript is Super Sexy _ JavaScript is Sexy

The document celebrates JavaScript as a versatile and appealing programming language, highlighting its attractive frontend and robust backend capabilities. It emphasizes JavaScript's accessibility for both beginners and experienced developers, and discusses the importance of learning frameworks like Backbone.js for building modern web applications. Additionally, it outlines a roadmap for mastering Backbone.js and encourages continuous learning in the JavaScript ecosystem.

Uploaded by

Hem Lok
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

JavaScript is Super Sexy | JavaScript is Sexy 7/22/14, 3:28 PM

JavaScript is Super Sexy


September 6 2 Years Ago

JavaScript is super sexy, mature, and stateful; it has an attractive frontend and a firm, kick ass backend. It is svelte and versatile, and its functions are dynamic.

It is affectionate to both hardcore pros and virgin noobs; it is even inviting to those who lack the prominence of programming know-how or the prestige of a CS degree.
Yep, even you can get down with JavaScript, no matter who you are—designers love JS, developers love JS, hackers love JS, and Code Academy has thousands signing up
for a date with JS.

Attractive Frontend Package


JS has an irresistibly sinful frontend with a mocha aroma that underscores its passion. It has a node, it is angular; it has a spine and a backbone for its curvy corners; its
agility is a knockout; and it can impress with its thick sproutcore that recently shaved to a desirable, lithe ember. Also impressive are its jade smile and its robust
jQuery abs, which make for exciting fun when it does express, if you prefer it that way, or when it bootstraps with arduino, for the adventurous type.

JS is agreeably the future, particularly with the advent of HTML5 and the simultaneous, ironic ‘dysfunction’ of Flash. As the chosen language of the web, it will be hot for
some time to come, this is evidenced by its recent ubiquity, meteoric rise, and modernizr upgrade.

JS Has Secrets

While JS’s sex appeal is obvious, curiously, we do not know JS’s gender. But we do know…ahem, JS does both Jasmine and JSON, separately. And we cannot be fooled
by its rainbow color—this is not a clue. Fortunately, JS’s gender is inconsequential and is best left a secret.

We also do not know JS’s age, because the algorithm to calculate programming languages’ years (how their age is calculated relative to that of a human’s age) is one of the
secrets of the universe. But with JS’s sprightly assets and attractions noted above, it is safe to say no one cares about JS’s specific age, since we already know it is “stateful
and mature” and most definitely at least a young adult—we know this from its well grown packages, frameworks, and thorough documentations accumulated ever since its
creation.

Not to worry, JS is not a senior citizen. Notwithstanding the couple of wrinkles on its ear lobes, which are actually birth marks or negligible defects (see Crockford’s
JavaScript-The Good Parts Appendix B: Bad Parts), JS is not even middle-aged yet—its youthful vigor is a giveaway.

Programmatic Proof of JS’s Sexiness


Note: The following code is a contrived example, it is purposely meant to be “sneaky” JavaScript (see paragraph below):
var sexy,
JavaScript;
function sexy() {
return this.sexy ? ("ugly. Rails is HOT.","Sexy!") : "no Python.";
}
JavaScript = {
sexy:sexy,
is:function (sexAppeal) {
sexAppeal = true;
if (!arguments[0]) {
console.log("JavaScript is " + this.sexy());
}
} };
JavaScript.is();

As you can see in the example code above, JS can be subtly sneaky, therefore, you must learn its idiosyncrasies before you get too involved with JS. You can start off with
a date with JS by reading How to Learn JavaScript Properly. And if you don’t understand the example code above, you definitely should learn JavaScript properly.

This new JS blog will try to help you learn JS and help you improve your JS skills, so you can confidently handle JS like a master, as you use it to make your projects
contemporary and appealing. JS cannot help your personal sex appeal, however. But if you are a hacker, designer, or programmer, you already have sex appeal, just be
careful and use it wisely.

Learn Backbone.js Completely


January 14 Last Year

(More Than Just a Complete Backbone.js Tutorial)


Duration: 25 to 30 hours
Prerequisite: JavaScript knowledge of 5/10

I provide you with a roadmap that I myself have used (indeed, I have refined it for this article) to learn Backbone.js thoroughly. It should take just about 30 hours to
complete this short, but thorough course.

After I learned Backbone.js, the first application I built was the following eCommerce web application for a client—a startup. I built Topics in This Post
the entire app, including the shopping cart, with Backbone.js and Node.js: What is Backbone.js and Why
https://buildandprice.superfocus.com/ Learn It?

Don’t Be Afraid, Backbone.js is Friendly Get The Two Backbone.js


Backbone.js is neither difficult to learn nor difficult to use, and the time you will spend learning to use this serviceable framework eBooks (one free one very cheap
will be well worth it, for you will learn how to properly build modern, single-page web applications and simultaneously see your —$4.99)
market value as a JS developer rise. Moreover, you will build JS applications considerably faster than you ever have. Roadmap to Mastering
Backbone.js
Before we Continue
Consider for a moment why you have chosen to learn Backbone.js out of all the major front-end JavaScript frameworks (Backbone.js, That’s It! (Almost)
Derby.js, Meteor.js, Knockout.js, Ember.js, Angular.js, and Spine.js). If you have chosen to learn Backbone.js because it is the most
Very Important Extras

file:///Users/shafiultareq/Downloads/JavaScript%20is%20Super%20Sexy%20%7C%20JavaScript%20is%20Sexy.html Page 1 of 60
JavaScript is Super Sexy | JavaScript is Sexy 7/22/14, 3:28 PM

popular JavaScript framework (which it is…well, watch out for Meteor.js meteoric rise lately), then you might want to read this in The Backbone.js
depth article by Addy Osmani, Journey Through The JavaScript MVC Jungle, and carefully consider all the criteria for selecting the Documentation is Great; You Will
best JS framework for your particular needs. Use it a Lot

I chose Backbone.js for the aforementioned eCommerce web application because I had only a few days to learn a JS framework and I
needed a proven JS framework since I was developing a web application for a client. And at the time, which was just a few months ago, Backbone.js had the more thorough
documentation and the most active community of all the JS MV* (some are MVC and others are MV-”Whatever”) frameworks. In addition, Backbone.js has the most
impressive list of real websites and web applications built with the framework. It is the most proven of the noted JS frameworks, as of this writing.

What is Backbone.js and Why Learn It?


You will not regret learning Backbone.js, because if you have never used a JS front-end framework before, you will have much pleasure developing applications with
Backbone.js.

What is Backbone.js?
Backbone.js is a JavaScript client-side (front-end) framework that helps to organize your code and makes it easier for you to develop single-page web applications. Simply
put, it makes the task of developing JavaScript applications considerably easier for you.

Why Learn Backbone.js


You should learn Backbone.js if:

You do not already use a front-end JavaScript framework and you intend to develop single-page web applications or complex JavaScript web applications.
You want to start programming JavaScript in a more organized, structured manner, eschewing the old way of having all of your JavaScript code mixed with HTML
and without separation of concerns (where the logic, the data—model—and the presentation are sufficiently decoupled).

Get The Two Backbone.js eBooks (one free one very cheap—$4.99)
1. First, download a copy of Addy Osmani’s Developing Backbone.js Applications

Addy Osmani is a prolific, yet altruistic, writer who writes book-length blog posts and articles on web technologies and programming, particularly JavaScript, and he
offers said writings free online. He has written on a myriad of JavaScript topics and just about all of his works are available online for free. However, since his book
Developing Backbone.js Applications is only $15.81, I recommend you own a copy of it and keep it as a reference, for you will need it.You can preorder it on
Amazon.

2. Instead of the Addy’s book, you can buy the book, “Backbone Tutorials,” at the link below:

https://leanpub.com/backbonetutorials

Note that most of this article focuses on the Developing Backbone.js Applications book, but you can use Backbone Tutorials, just follow along with the relevant
topics, accordingly.

Roadmap to Mastering Backbone.js


Note that all the links below open in a new tab so that you can read the articles and quickly come back and follow the roadmap.

1. If you already know JavaScript very well, and you feel invincible when you sit to code in JavaScript, carry on with step 2 below.

If you don’t know JavaScript well enough to develop a full, interactive quiz application with just JavaScript (no jQuery), you should learn JavaScript properly.

If you know enough JavaScript and want to proceed, but you feel you need a JavaScript refresher, read these 3 articles (in the order they are listed):
— JavaScript Objects in Detail
— JavaScript Variable Scope and Hoisting Explained
— (Must Read) Understand JavaScript Closures With Ease

2. Read the following 4 blog posts for the conceptual understanding of Model, View, Router, and Collections:
— What is a model?
— What is a view?
— What is a router?
— What is a collection?
3. Read the entire tutorial at the link below (note that it is a bit old, but still valid) and study and understand it carefully, but don’t try to build the app just yet:
Backbone.js Wine Cellar Tutorial — Part 1: Getting Started
4. Read Developing Backbone.js Applications from the beginning (Prelude) to the Backbone Basics chapter.
5. Read these 2 blog posts:
— The Responsibilities Of The Various Pieces Of Backbone.js
— 3 Stages Of A Backbone Application’s Startup
6. You should be able to build the simple Backbone.js application you studied in section 3 above. Return to that tutorial and build the application.
7. Return to Developing Backbone.js Applications and read the Exercise 1 chapter (and build the application), then read the chapter titled Common Problems &
Solutions followed by the chapter Exercise 2 (and build the application in exercise 2).
8. Read the Modular Development chapter and build whichever application(s) you want to build from this chapter. You needn’t build all of the example applications.
9. Follow these two tutorials (these are a bit old too, but still accurate):
—Backbone.js Wine Cellar Tutorial — Part 2: CRUD
—Backbone.js Lessons Learned and Improved Sample App (This is a MUST READ)
10. These are 4 MUST READ articles:
— (Learn how to communicate among views and subviews)
References, Routing, And The Event Aggregator: Coordinating Views In Backbone.js
— Revisiting The Backbone Event Aggregator: Lessons Learned
— (Managing Page Transitions In Backbone Apps)
Learn How to transition between views and how to properly dispose of viewsZombies! RUN!
— Why Should I Use Backbone.Marionette Instead Of … ?

file:///Users/shafiultareq/Downloads/JavaScript%20is%20Super%20Sexy%20%7C%20JavaScript%20is%20Sexy.html Page 2 of 60
JavaScript is Super Sexy | JavaScript is Sexy 7/22/14, 3:28 PM

That’s It! (Almost)


At this juncture, you have learned enough to build any Backbone.js application: you have gone from absolute beginner to attainment in under 30 hours, if you stayed the
course.

But to really understand and retain what you have learned, you must build a real, single-page web application.

11. If you are involved with backend development as well as front end, you should read my post, Learn Node.js Completely, if you don’t already know Node.js

12. With a complete understanding of Node.js and Backbone.js, you are ready to build any type of web application. You can go ahead and build a startup at this juncture, if
you are intrepid.

But before you head off on your adventure, build the NodeApp web application at the link below; this exercise provides a real-world exercise in Node.js/Backbone.js web
application development:
http://dailyjs.com/web-app.html

If on the other hand you only develop on the front end, you should still learn Node.js, for if you manage to Backbone.js, you can easily learn Node.js.

Very Important Extras


1. Read the following chapters in Developing Backbone.js Applications to further advance your knowledge on the Backbone.js ecosystem:
— Backbone Extensions
— Backbone Boilerplate And Grunt-BBB
— Mobile Applications
— Unit Testing
2. Learn Handlebars Templating Engine
Handlebars templating engine is much more robust and feature rich than the simple template engine bundled with Backbone.js (The template used in Backbone.js by
default is from the Underscore.js library, and Underscore.js is Backbone.js’s lone dependency).
Read my post, Handlebars.js Tutorial: Learn Everything About Handlebars.js JavaScript Templating.

The Backbone.js Documentation is Great; You Will Use it a Lot


Once you start developing on your own, you will find yourself making frequent stops to the Backbone.js documentation. This will likely be the website you visit most
often, when you need help figuring out how to do any myriad of things while developing a Backbone.js application. Here is the link:
http://backbonejs.org/

Pilgrimage to JavaScript Mastery


January 20 Last Year

(From Absolute Beginner to Attainment)


Join me as we embark on a pilgrimage to JavaScript mastery—where the eminent few reside in a consciousness of JavaScript enlightenment and programming prominence.
This mastery is a state of mindfulness that such experts as Douglas Crockford, John Resig, and Nicholas Zackas, amongst others, possess, and it is this state we are destined
for, even as we have no assurance we will arrive there and it is unlikely we will ever get there.

Yes, we will endure inevitable bugs, tireless frustrations, ever-changing frameworks, and unknown circumstances that we must debug and resolve. But we are guaranteed
insightful discoveries, euphoric accomplishments, and technical scholarship while on this pilgrimage. And even though we may never experience JavaScript enlightenment
quite like Crockford and Zakas, we will be better programmers, accomplished developers, and perhaps successful entrepreneurs along the way.

On this pilgrimage, we will learn mostly from books (that we should each own) by Nicholas C. Zakas, David Flanagan, David Herman (new author), Douglas Crockford,
and others, and from outstanding blog posts by prolific JavaScript bloggers like Addy Osmani.

Our journey has just begun; everyone is invited to join anytime. We have already learned JavaScript properly and Backbone.js completely, but we have much to learn. We
will thoroughly understand sixteen JavaScript concepts that we must know well, and we will continue to learn scores of advanced JavaScript topics and modern JavaScript
frameworks along the way.

Later, we will have a place to show our projects and encourage each other.

Keep an eye on the Upcoming Posts section in the sidebar for where our journey will take us next.

JavaScript Prototype in Plain Language


January 25 Last Year

Prototype is a fundamental concept that every JavaScript developer must understand, and this post aims to explain JavaScript’s prototype in plain, detailed language. If
you don’t understand JavaScript’s prototype after reading this blog post, please post your questions in the comments below, I will personally answer all questions.

To understand prototype in JavaScript you must understand JavaScript’s objects. If you aren’t already familiar with objects, you should read my post JavaScript Objects in
Detail. Also, know that a property is simply a variable defined on a function.

There are two interrelated concepts with prototype in JavaScript:

1. First, there is a prototype property that every JavaScript function has (it is empty by default), and you attach properties and methods on this prototype property
when you want to implement inheritance.Note that this prototype property is not enumerable: it is not accessible in a for/in loop. But Firefox, and most versions of

file:///Users/shafiultareq/Downloads/JavaScript%20is%20Super%20Sexy%20%7C%20JavaScript%20is%20Sexy.html Page 3 of 60
JavaScript is Super Sexy | JavaScript is Sexy 7/22/14, 3:28 PM

Safari and Chrome, have a __proto__ “pseudo” property (an alternative way) that allows you to access an object’s prototype property. You will likely never use this
__proto__ pseudo property, but know that it exists and it is simply a way to access an object’s prototype property in some browsers.

The prototype property is used primarily for inheritance: you add methods and properties on a function’s prototype property to make those methods and properties
available to instances of that function.

Here is a very simple example of inheritance with the prototype property (more on inheritance later):

function PrintStuff (myDocuments) {


this.documents = myDocuments;
}

// We add the print () method to PrintStuff prototype property so that other instances (objects) can inherit it:
PrintStuff.prototype.print = function () {
console.log(this.documents);
}

// Create a new object with the PrintStuff () constructor, thus allowing this new object to inherit PrintStuff's properties and methods.
var newObj = new PrintStuff ("I am a new Object and I can print.");

// newObj inherited all the properties and methods, including the print method, from the PrintStuff function. Now newObj can call print direct
newObj.print (); //I am a new Object and I can print.

2. The second concept with prototype in JavaScript is the prototype attribute. Think of the prototype attribute as a characteristic of the object; this characteristic tells
us the object’s “parent”. In simple terms: An object’s prototype attribute points to the object’s “parent”—the object it inherited its properties from. The prototype
attribute is normally referred to as the prototype object, and it is set automatically when you create a new object.To expound on this: Every object inherits properties
from some other object, and it is this other object that is the object’s prototype attribute or “parent.” (You can think of the prototype attribute as the lineage or the
parent). In the example code above, newObj‘s prototype is PrintStuff.prototype.

Note: All objects have attributes just like object properties have attributes. And the object attributes are prototype, class, and extensible attributes. It is this prototype
attribute that we are discussing in this second example.

Also note that the __proto__ “pseudo” property contains an object’s prototype object (the parent object it inherited its methods and properties from).

Constructor
Before we continue, let’s briefly examine the constructor. A constructor is a function used for initializing new objects, and you use the new keyword to call the constructor.
For example:
function Account () {
}
// This is the use of the Account constructor to create the userAccount object.
var userAccount = new Account ();

Moreover, all objects that inherit from another object also inherit a constructor property. And this constructor property is simply a property (like any variable) that holds or
points to the constructor of the object.

//The constructor in this example is Object ()


var myObj = new Object ();
// And if you later want to find the myObj constructor:
console.log(myObj.constructor); // Object()

// Another example: Account () is the constructor


var userAccount = new Account ();
// Find the userAccount object's constructor
console.log(userAccount.constructor); // Account()

Prototype Attribute of Objects Created with new Object () or Object Literal


All objects created with object literals and with the Object constructor inherits from Object.prototype. Therefore, Object.prototype is the prototype attribute (or the
prototype object) of all objects created with new Object () or with {}. Object.prototype itself does not inherit any methods or properties from any other object.

// The userAccount object inherits from Object and as such its prototype attribute is Object.prototype.
var userAccount = new Object ();

// This demonstrates the use of an object literal to create the userAccount object; the userAccount object inherits from Object; therefore, its pro
var userAccount = {name: “Mike”}

Prototype Attribute of Objects Created With a Constructor Function


Objects created with the new keyword and any constructor other than the Object () constructor, get their prototype from the constructor function.

For Example:

function Account () {

}
var userAccount = new Account () // userAccount initialized with the Account () constructor and as such its prototype attribute (or prototype objec

Similarly, any array such as var myArray = new Array (), gets its prototype from Array.prototype and it inherits Array.prototype’s properties.

So, there are two general ways an object’s prototype attribute is set when an object is created:

1. If an object is created with an object literal (var newObj = {}), it inherits properties from Object.prototype and we say its prototype object (or prototype attribute) is
Object.prototype.
2. If an object is created from a constructor function such as new Object (), new Fruit () or new Array () or new Anything (), it inherits from that constructor (Object (),
Fruit (), Array (), or Anything ()). For example, with a function such as Fruit (), each time we create a new instance of Fruit (var aFruit = new Fruit ()), the new
instance’s prototype is assigned the prototype from the Fruit constructor, which is Fruit.prototype.Any object that was created with new Array () will have
Array.prototype as its prototype. An object created with new Fruit () will have Fruit.prototype as its prototype. And any object created with the Object constructor
(Obj (), such as var anObj = new Object() ) inherits from Object.prototype.

It is important to know that in ECMAScript 5, you can create objects with an Object.create() method that allows you to set the new object’s prototype object. We will cover

file:///Users/shafiultareq/Downloads/JavaScript%20is%20Super%20Sexy%20%7C%20JavaScript%20is%20Sexy.html Page 4 of 60
JavaScript is Super Sexy | JavaScript is Sexy 7/22/14, 3:28 PM

ECMAScript 5 in a later post.

Why is Prototype Important and When is it Used?


These are two important ways the prototype is used in JavaScript, as we noted above:

1. Prototype Property: Prototype-based Inheritance


Prototype is important in JavaScript because JavaScript does not have classical inheritance based on Classes (as most object oriented languages do), and therefore all
inheritance in JavaScript is made possible through the prototype property. JavaScript has a prototype-based inheritance mechanism.Inheritance is a programming
paradigm where objects (or Classes in some languages) can inherit properties and methods from other objects (or Classes). In JavaScript, you implement inheritance
with the prototype property. For example, you can create a Fruit function (an object, since all functions in JavaScript are objects) and add properties and methods on
the Fruit prototype property, and all instances of the Fruit function will inherit all the Fruit’s properties and methods.

Demonstration of Inheritance in JavaScript:

function Plant () {
this.country = "Mexico";
this.isOrganic = true;
}

// Add the showNameAndColor method to the Plant prototype property


Plant.prototype.showNameAndColor = function () {
console.log("I am a " + this.name + " and my color is " + this.color);
}

// Add the amIOrganic method to the Plant prototype property


Plant.prototype.amIOrganic = function () {
if (this.isOrganic)
console.log("I am organic, Baby!");
}

function Fruit (fruitName, fruitColor) {


this.name = fruitName;
this.color = fruitColor;
}

// Set the Fruit's prototype to Plant's constructor, thus inheriting all of Plant.prototype methods and properties.
Fruit.prototype = new Plant ();

// Creates a new object, aBanana, with the Fruit constructor


var aBanana = new Fruit ("Banana", "Yellow");

// Here, aBanana uses the name property from the aBanana object prototype, which is Fruit.prototype:
console.log(aBanana.name); // Banana

// Uses the showNameAndColor method from the Fruit object prototype, which is Plant.prototype. The aBanana object inherits all the properties
console.log(aBanana.showNameAndColor()); // I am a Banana and my color is yellow.

Note that the showNameAndColor method was inherited by the aBanana object even though it was defined all the way up the prototype chain on the Plant.prototype
object.

Indeed, any object that uses the Fruit () constructor will inherit all the Fruit.prototype properties and methods and all the properties and methods from the Fruit’s
prototype, which is Plant.prototype. This is the principal manner in which inheritance is implemented in JavaScript and the integral role the prototype chain has
in the process.

For more in-depth coverage on Objective Oriented Programming in JavaScript, get Nicholas Zakas’s Principles of Object-Oriented Programming in JavaScript (it is
only $14.99).

2. Prototype Attribute: Accessing Properties on Objects


Prototype is also important for accessing properties and methods of objects. The prototype attribute (or prototype object) of any object is the “parent” object where
the inherited properties were originally defined.This is loosely analogous to the way you might inherit your surname from your father—he is your “prototype parent.”
If we wanted to find out where your surname came from, we would first check to see if you created it yourself; if not, the search will move to your prototype parent
to see if you inherited it from him. If it was not created by him, the search continues to his father (your father’s prototype parent).

Similarly, if you want to access a property of an object, the search for the property begins directly on the object. If the JS runtime can’t find the property there, it then
looks for the property on the object’s prototype—the object it inherited its properties from.
If the property is not found on the object’s prototype, the search for the property then moves to prototype of the object’s prototype (the father of the object’s father—
the grandfather). And this continues until there is no more prototype (no more great-grand father; no more lineage to follow). This in essence is the prototype
chain: the chain from an object’s prototype to its prototype’s prototype and onwards. And JavaScript uses this prototype chain to look for properties and methods of
an object.
If the property does not exist on any of the object’s prototype in its prototype chain, then the property does not exist and undefined is returned.

This prototype chain mechanism is essentially the same concept we have discussed above with the prototype-based inheritance, except we are now focusing
specifically on how JavaScript accesses object properties and methods via the prototype object.

This example demonstrates the prototype chain of an object’s prototype object:

var myFriends = {name: "Pete"};

// To find the name property below, the search will begin directly on the myFriends object and will immediately find the name property because
console.log(myFriends.name);

// In this example, the search for the toString () method will also begin on the myFriends’ object, but because we never created a toString me

// And since all objects created with the object literal inherits from Object.prototype, the toString method will be found on Object.prototype

myFriends.toString ();

Object.prototype Properties Inherited by all Objects


All objects in JavaScript inherit properties and methods from Object.prototype. These inherited properties and methods are constructor, hasOwnProperty (),
isPrototypeOf (), propertyIsEnumerable (), toLocaleString (), toString (), and valueOf (). ECMAScript 5 also adds 4 accessor methods to Object.prototype.

file:///Users/shafiultareq/Downloads/JavaScript%20is%20Super%20Sexy%20%7C%20JavaScript%20is%20Sexy.html Page 5 of 60
JavaScript is Super Sexy | JavaScript is Sexy 7/22/14, 3:28 PM

Here is another example of the prototype chain:


function People () {
this.superstar = "Michael Jackson";
}
// Define "athlete" property on the People prototype so that "athlete" is accessible by all objects that use the People () constructor.
People.prototype.athlete = "Tiger Woods";

var famousPerson = new People ();


famousPerson.superstar = "Steve Jobs";

// The search for superstar will first look for the superstar property on the famousPerson object, and since we defined it there, that is the
console.log (famousPerson.superstar); // Steve Jobs

// Note that in ECMAScript 5 you can set a property to read only, and in that case you cannot overwrite it as we just did.

// This will show the property from the famousPerson prototype (People.prototype), since the athlete property was not defined on the famousPer
console.log (famousPerson.athlete); // Tiger Woods

// In this example, the search proceeds up the prototype chain and find the toString method on Object.prototype, from which the Fruit object i
console.log (famousPerson.toString()); // [object Object]

All built-in constructors (Array (), Number (), String (), etc.) were created from the Object constructor, and as such their prototype is Object.prototype.

Check back on February 7th for a quiz on JavaScript Prototype.

Additional Information
For more on JavaScript Objects, read Chapter 6 of JavaScript: The Definitive Guide (6th Edition, May 2011) by David Flanagan.

JavaScript Objects in Detail


January 27 Last Year

JavaScript’s core—most often used and most fundamental—data type is the Object data type. JavaScript has one complex data type, the Object data type, and it has five
simple data types: Number, String, Boolean, Undefined, and Null. Note that these simple (primitive) data types are immutable, they cannot be changed, while objects are
mutable.

What is an Object
An object is an unordered list of primitive data (and sometimes reference data types) types that are stored as name-value pairs. Each item in the list is called a property
(functions are called methods) and each property name has to be unique and can be a string or a number.

Here is a simple object:

var myFirstObject = {firstName: "Richard", favoriteAuthor: "Conrad"};

To reiterate: Think of an object as a list that contains items and each item (a property) in the list is stored by a name-value pair. The property names in the example above
are firstName and favoriteAuthor. And the values for each are “Richard” and “Conrad.”

Property names can be a string or a number, but if the property name is a number, it has to be accessed with the bracket notation. More on bracket notation later. Here is
another example of objects with numbers as the property name:

var ageGroup = {30: "Children", 100:"Very Old"};


console.log(ageGroup.30) // This will throw an error
// This is how you will access the value of the property 30, to get value "Children"
console.log(ageGroup["30"]); // Children

//It is best to avoid using numbers as property names.

As a JavaScript developer you will most often use the object data type, mostly for storing data and for creating your own custom methods and functions.

Reference Data Type and Primitive Data Types


One of the main differences between reference data type and primitive data types is reference data type’s value is stored as a reference, it is not stored directly on the
variable, as a value, as the primitive data types are. For example:

// The primitive data type String is stored as a value


var person = "Kobe";
var anotherPerson = person; // anotherPerson = the value of person
person = "Bryant"; // value of person changed

console.log(anotherPerson); // Kobe
console.log(person); // Bryant

It is worth noting that even though we changed person to “Bryant,” the anotherPerson variable still retains the value that person had.

Compare the primitive data saved-as-value demonstrated above with the save-as-reference for objects:

var person = {name: "Kobe"};


var anotherPerson = person;
person.name = "Bryant";

console.log(anotherPerson.name); // Bryant
console.log(person.name); // Bryant

In this example, we copied the person object to anotherPerson, but because the value in person was stored as a reference and not an actual value, when we changed the
person.name property to “Bryant” the anotherPerson reflected the change because it never stored an actual copy of it’s own value of the person’s properties, it only had a
reference to it.

Object Data Properties Have Attributes

file:///Users/shafiultareq/Downloads/JavaScript%20is%20Super%20Sexy%20%7C%20JavaScript%20is%20Sexy.html Page 6 of 60
JavaScript is Super Sexy | JavaScript is Sexy 7/22/14, 3:28 PM

Each data property (object property that store data) has not only the name-value pair, but also 3 attributes (the three attributes are set to true by default):
—Configurable Attribute: Specifies whether the property can be deleted or changed.
— Enumerable: Specifies whether the property can be returned in a for/in loop.
— Writable: Specifies whether the property can be changed.

Note that ECMAScript 5 specifies accessor properties along with the data properties noted above. And the accessor properties are functions (getters and setters). We will
learn more about ECMAScript 5 in an already-scheduled post slated for February 15.

Creating Objects
These are the two common ways to create objects:

1. Object Literals
The most common and, indeed, the easiest way to create objects is with the object literal described here:
// This is an empty object initialized using the object literal notation
var myBooks = {};

// This is an object with 4 items, again using object literal


var mango = {
color: "yellow",
shape: "round",
sweetness: 8,

howSweetAmI: function () {
console.log("Hmm Hmm Good");
}
}

2. Object Constructor
The second most common way to create objects is with Object constructor. A constructor is a function used for initializing new objects, and you use the new keyword
to call the constructor.

var mango = new Object ();


mango.color = "yellow";
mango.shape= "round";
mango.sweetness = 8;

mango.howSweetAmI = function () {
console.log("Hmm Hmm Good");
}

While you can use some reserved word such as “for” as property names in your objects, it is wise to avoid this altogether.

Objects can contain any other data type, including Numbers, Arrays, and even other Objects.

Practical Patterns for Creating Objects


For simple objects that may only ever be used once in your application to store data, the two methods used above would suffice for creating objects.

Imagine you have an application that displays fruits and detail about each fruit. All fruits in your application have these properties: color, shape, sweetness, cost, and a
showName function. It would be quite tedious and counterproductive to type the following every time you want to create a new fruit object.

var mangoFruit = {
color: "yellow",
sweetness: 8,
fruitName: "Mango",
nativeToLand: ["South America", "Central America"],

showName: function () {
console.log("This is " + this.fruitName);
},
nativeTo: function () {
this.nativeToLand.forEach(function (eachCountry) {
console.log("Grown in:" + eachCountry);
});
}
}

If you have 10 fruits, you will have to add the same code 10 times. And what if you had to make a change to the nativeTo function? You will have to make the change in 10
different places. Now extrapolate this to adding objects for members on a website and suddenly you realized the manner in which we have created objects so far is not ideal
objects that will have instances, particularly when developing large applications.

To solve these repetitive problems, software engineers have invented patterns (solutions for repetitive and common tasks) to make developing applications more efficient
and streamlined.

Here are two common patterns for creating objects. If you have done the Learn JavaScript Properly course, you would have seen the lessons in the Code Academy used this
first pattern frequently:

1. Constructor Pattern for Creating Objects


function Fruit (theColor, theSweetness, theFruitName, theNativeToLand) {

this.color = theColor;
this.sweetness = theSweetness;
this.fruitName = theFruitName;
this.nativeToLand = theNativeToLand;

this.showName = function () {
console.log("This is a " + this.fruitName);
}

this.nativeTo = function () {

file:///Users/shafiultareq/Downloads/JavaScript%20is%20Super%20Sexy%20%7C%20JavaScript%20is%20Sexy.html Page 7 of 60
JavaScript is Super Sexy | JavaScript is Sexy 7/22/14, 3:28 PM

this.nativeToLand.forEach(function (eachCountry) {
console.log("Grown in:" + eachCountry);
});
}

With this pattern in place, it is very easy to create all sorts of fruits. Thus:

var mangoFruit = new Fruit ("Yellow", 8, "Mango", ["South America", "Central America", "West Africa"]);
mangoFruit.showName(); // This is a Mango.
mangoFruit.nativeTo();
//Grown in:South America
// Grown in:Central America
// Grown in:West Africa

var pineappleFruit = new Fruit ("Brown", 5, "Pineapple", ["United States"]);


pineappleFruit.showName(); // This is a Pineapple.

If you had to change the fruitName function, you only had to do it in one location. The pattern encapsulates all the functionalities and characteristics of all the fruits
in by making just the single Fruit function with inheritance.

Notes:
— An inherited property is defined on the object’s prototype property. For example: someObject.prototype.firstName = “rich”;

— An own property is defined directly on the object itself, for example:


// Let’s create an object first:
var aMango = new Fruit ();
// Now we define the mangoSpice property directly on the aMango object
// Because we define the mangoSpice property directly on the aMango object, it is an own property of aMango, not an inherited property.
aMango.mangoSpice = “some value”;

— To access a property of an object, we use object.property, for example:


console.log(aMango.mangoSpice); // “some value”

— To invoke a method of an object, we use object.method(), for example:


// First, lets add a method
aMango.printStuff = function () {return “Printing”;}

// Now we can invoke the printStuff method:


aMango.printStuff ();

2. Prototype Pattern for Creating Objects


function Fruit () {

Fruit.prototype.color = "Yellow";
Fruit.prototype.sweetness = 7;
Fruit.prototype.fruitName = "Generic Fruit";
Fruit.prototype.nativeToLand = "USA";

Fruit.prototype.showName = function () {
console.log("This is a " + this.fruitName);
}

Fruit.prototype.nativeTo = function () {
console.log("Grown in:" + this.nativeToLand);
}

And this is how we call the Fruit () constructor in this prototype pattern:
var mangoFruit = new Fruit ();
mangoFruit.showName(); //
mangoFruit.nativeTo();
// This is a Generic Fruit
// Grown in:USA

Further Reading
For a complete discussion on these two patterns and a thorough explanation of how each work and the disadvantages of each, read Chapter 6 of Professional JavaScript for
Web Developers. You will also learn which pattern Zakas recommends as the best one to use (Hint: it is neither of the 2 above).

How to Access Properties on an Object


The two primary ways of accessing properties of an object are with dot notation and bracket notation.

1. Dot Notation
// We have been using dot notation so far in the examples above, here is another example again:
var book = {title: "Ways to Go", pages: 280, bookMark1:"Page 20"};

// To access the properties of the book object with dot notation, you do this:
console.log ( book.title); // Ways to Go
console.log ( book.pages); // 280

2. Bracket Notation
// To access the properties of the book object with bracket notation, you do this:
console.log ( book["title"]); //Ways to Go
console.log ( book["pages"]); // 280

file:///Users/shafiultareq/Downloads/JavaScript%20is%20Super%20Sexy%20%7C%20JavaScript%20is%20Sexy.html Page 8 of 60
JavaScript is Super Sexy | JavaScript is Sexy 7/22/14, 3:28 PM

//Or, in case you have the property name in a variable:


var bookTitle = "title";
console.log ( book[bookTitle]); // Ways to Go
console.log (book["bookMark" + 1]); // Page 20

Accessing a property on an object that does not exist will result in undefined.

Own and Inherited Properties


Objects have inherited properties and own properties. The own properties are properties that were defined on the object, while the inherited properties were inherited from
the object’s Prototype object.

To find out if a property exists on an object (either as an inherited or an own property), you use the in operator:

// Create a new school object with a property name schoolName


var school = {schoolName:"MIT"};

// Prints true because schoolName is an own property on the school object


console.log("schoolName" in school); // true

// Prints false because we did not define a schoolType property on the school object, and neither did the object inherit a schoolType property from
console.log("schoolType" in school); // false

// Prints true because the school object inherited the toString method from Object.prototype.
console.log("toString" in school); // true

hasOwnProperty
To find out if an object has a specific property as one of its own property, you use the hasOwnProperty method. This method is very useful because from time to time you
need to enumerate an object and you want only the own properties, not the inherited ones.

// Create a new school object with a property name schoolName


var school = {schoolName:"MIT"};

// Prints true because schoolName is an own property on the school object


console.log(school.hasOwnProperty ("schoolName")); // true

// Prints false because the school object inherited the toString method from Object.prototype, therefore toString is not an own property of the sch
console.log(school.hasOwnProperty ("toString")); // false

Accessing and Enumerating Properties on Objects


To access the enumerable (own and inherited) properties on objects, you use the for/in loop or a general for loop.

// Create a new school object with 3 own properties: schoolName, schoolAccredited, and schoolLocation.
var school = {schoolName:"MIT", schoolAccredited: true, schoolLocation:"Massachusetts"};

//Use of the for/in loop to access the properties in the school object
for (var eachItem in school) {
console.log(eachItem); // Prints schoolName, schoolAccredited, schoolLocation

Accessing Inherited Properties


Properties inherited from Object.prototype are not enumerable, so the for/in loop does not show them. However, inherited properties that are enumerable are revealed in the
for/in loop iteration.
For example:
//Use of the for/in loop to access the properties in the school object
for (var eachItem in school) {
console.log(eachItem); // Prints schoolName, schoolAccredited, schoolLocation

// Create a new HigherLearning function that the school object will inherit from.
/* SIDE NOTE: As Wilson (an astute reader) correctly pointed out in the comments below, the educationLevel property is not actually inherited by ob
*/

function HigherLearning () {
this.educationLevel = "University";
}

// Implement inheritance with the HigherLearning constructor


var school = new HigherLearning ();
school.schoolName = "MIT";
school.schoolAccredited = true;
school.schoolLocation = "Massachusetts";

//Use of the for/in loop to access the properties in the school object
for (var eachItem in school) {
console.log(eachItem); // Prints educationLevel, schoolName, schoolAccredited, and schoolLocation
}

In the last example, note the educationLevel property that was defined on the HigherLearning function is listed as one of the school’s properties, even though
educationLevel is not an own property—it was inherited.

Object’s Prototype Attribute and Prototype Property


The prototype attribute and prototype property of an object are critically important concepts to understand in JavaScript. Read my post JavaScript Prototype in Plain,
Detailed Language for more.

Deleting Properties of an Object


To delete a property from an object, you use the delete operator. You cannot delete properties that were inherited, nor can you delete properties with their attributes set to
configurable. You must delete the inherited properties on the prototype object (where the properties were defined). Also, you cannot delete properties of the global object,

file:///Users/shafiultareq/Downloads/JavaScript%20is%20Super%20Sexy%20%7C%20JavaScript%20is%20Sexy.html Page 9 of 60
JavaScript is Super Sexy | JavaScript is Sexy 7/22/14, 3:28 PM

which were declared with the var keyword.

The delete operator returns true if the delete was successful. And surprisingly, it also returns true if the property to delete was nonexistent or the property could not be
deleted (such as non-configurable or not owned by the object).

These examples illustrate:

var christmasList = {mike:"Book", jason:"sweater" }


delete christmasList.mike; // deletes the mike property

for (var people in christmasList) {


console.log(people);
}
// Prints only jason
// The mike property was deleted

delete christmasList.toString; // returns true, but toString not deleted because it is an inherited method

// Here we call the toString method and it works just fine—wasn’t deleted
christmasList.toString(); //"[object Object]"

// You can delete a property of an instance if the property is an own property of that instance. For example, we can delete the educationLevel prop

console.log(school.hasOwnProperty("educationLevel")); true
// educationLevel is an own property on school, so we can delete it
delete school.educationLevel; true

// The educationLevel property was deleted from the school instance


console.log(school.educationLevel); undefined

// But the educationLevel property is still on the HigherLearning function


var newSchool = new HigherLearning ();
console.log(newSchool.educationLevel); // University

// If we had defined a property on the HigherLearning function's prototype, such as this educationLevel2 property:
HigherLearning.prototype.educationLevel2 = "University 2";

// Then the educationLevel2 property on the instances of HigherLearning would not be own property.

// The educationLevel2 property is not an own property on the school instance


console.log(school.hasOwnProperty("educationLevel2")); false
console.log(school.educationLevel2); // University 2

// Let's try to delete the inherited educationLevel2 property


delete school.educationLevel2; true (always returns true, as noted earlier)

// The inherited educationLevel2 property was not deleted


console.log(school.educationLevel2); University 2

Serialize and Deserialize Objects


To transfer your objects via HTTP or to otherwise convert it to a string, you will need to serialize it (convert it to a string); you can use the JSON.stringify function to
serialize your objects. Note that prior to ECMAScript 5, you had to use a popular json2 library (by Douglas Crockford) to get the JSON.stringify function. It is now
standardized in ECMAScript 5.

To Deserialize your object (convert it to an object from a string), you use the JSON.parse function from the same json2 library. This function too has been standardized by
ECMAScript 5.

JSON.stringify Examples:

var christmasList = {mike:"Book", jason:"sweater", chelsea:"iPad" }


JSON.stringify (christmasList);
// Prints this string:
// "{"mike":"Book","jason":"sweater","chels":"iPad"}"

// To print a stringified object with formatting, add "null" and "4" as parameters:
JSON.stringify (christmasList, null, 4);
// "{
"mike": "Book",
"jason": "sweater",
"chels": "iPad"
}"

// JSON.parse Examples \\
// The following is a JSON string, so we cannot access the properties with dot notation (like christmasListStr.mike)
var christmasListStr = '{"mike":"Book","jason":"sweater","chels":"iPad"}';

// Let’s convert it to an object


var christmasListObj = JSON.parse (christmasListStr);

// Now that it is an object, we use dot notation


console.log(christmasListObj.mike); // Book

For more detailed coverage of JavaScript Objects, including ECMAScript 5 additions for dealing with objects, read chapter 6 of JavaScript: The Definitive Guide 6th
Edition.

JavaScript Variable Scope and Hoisting Explained


January 31 Last Year

In this post, we will learn JavaScript’s variable scope and hoisting and all the idiosyncrasies of both.

file:///Users/shafiultareq/Downloads/JavaScript%20is%20Super%20Sexy%20%7C%20JavaScript%20is%20Sexy.html Page 10 of 60
JavaScript is Super Sexy | JavaScript is Sexy 7/22/14, 3:28 PM

It is imperative that we understand how variable scope and variable hoisting work in JavaScript. These concepts might seem straightforward, but they are not. There are
some important subtleties that we must understand, if we want to succeed in JavaScript development.

Variable Scope
A variable’s scope is the context in which the variable exists. It specifies from where you can access a variable and whether you have access to the variable in that context.

Variables have either a local scope or a global scope.

Local Variables (Function-level scope)


Unlike most programming languages, JavaScript does not have block-level scope (variables scoped to surrounding curly brackets); instead, JavaScript has function-level
scope. Variables declared within a function are local variables and are only accessible within that function or by functions inside that function. See my post on Closures for
more on accessing variables in outer functions from inner functions.

Demonstration of Function-Level Scope


var name = "Richard";

function showName () {
var name = "Jack"; // local variable; only accessible in this showName function
console.log (name); // Jack
}
console.log (name); // Richard: the global variable

No Block-Level Scope

var name = "Richard";


// the blocks in this if statement do not create a local context for the name variable
if (name) {
name = "Jack"; // this name is the global name variable and it is being changed to "Jack" here
console.log (name); // Jack: still the global variable
}

// Here, the name variable is the same global name variable, but it was changed in the if statement
console.log (name); // Jack

If You Don’t Declare Your Local Variables, Trouble is Nigh


Always declare your local variables before you use them. In fact, you should use JSHint to check your code for syntax errors and style guides. Here is the trouble
with not declaring local variables:

// If you don't declare your local variables with the var keyword, they are part of the global scope
var name = "Michael Jackson";

function showCelebrityName () {
console.log (name);
}

function showOrdinaryPersonName () {
name = "Johnny Evers";
console.log (name);
}
showCelebrityName (); // Michael Jackson

// name is not a local variable, it simply changes the global name variable
showOrdinaryPersonName (); // Johnny Evers

// The global variable is now Johnny Evers, not the celebrity name anymore
showCelebrityName (); // Johnny Evers

// The solution is to declare your local variable with the var keyword
function showOrdinaryPersonName () {
var name = "Johnny Evers"; // Now name is always a local variable and it will not overwrite the global variable
console.log (name);
}

Local Variables Have Priority Over Global Variables in Functions


If you declare a global variable and a local variable with the same name, the local variable will have priority when you attempt to use the variable inside a function
(local scope):

var name = "Paul";

function users () {
// Here, the name variable is local and it takes precedence over the same name variable in the global scope
var name = "Jack";

// The search for name starts right here inside the function before it attempts to look outside the function in the global scope
console.log (name);
}

users (); // Jack

Global Variables
All variables declared outside a function are in the global scope. In the browser, which is what we are concerned with as front-end developers, the global context or scope is
the window object (or the entire HTML document).

Any variable declared or initialized outside a function is a global variable, and it is therefore available to the entire application. For example:
// To declare a global variable, you could do any of the following:
var myName = "Richard";

// or even
firstName = "Richard";

file:///Users/shafiultareq/Downloads/JavaScript%20is%20Super%20Sexy%20%7C%20JavaScript%20is%20Sexy.html Page 11 of 60
JavaScript is Super Sexy | JavaScript is Sexy 7/22/14, 3:28 PM

// or
var name; //
name;
</pre>

It is important to note that all global variables are attached to the window object. So, all the global variables we just declared can be acce

console.log(window.myName); // Richard;

// or
console.log("myName" in window); // true
console.log("firstName" in window); // true
</pre>

If a variable is initialized (assigned a value) without first being declared with the var keyword, it is automatically added to the global context and it is thus a global
variable:
function showAge () {
// Age is a global variable because it was not declared with the var keyword inside this function
age = 90;
console.log(age);//
}

showAge (); // 90

// Age is in the global context, so it is available here, too


console.log(age); // 90

Demonstration of variables that are in the Global scope even as they seem otherwise:

// Both firstName variables are in the global scope, even though the second one is surrounded by a block {}.
var firstName = "Richard";
{
var firstName = "Bob";
}

// To reiterate: JavaScript does not have block-level scope

// The second declaration of firstName simply re-declares and overwrites the first one
console.log (firstName); // Bob

Another example

for (var i = 1; i <= 10; i++) {


console.log (i); // outputs 1, 2, 3, 4, 5, 6, 7, 8, 9, 10;
};

// The variable i is a global variable and it is accessible in the following function with the last value it was assigned above
function aNumber () {
console.log(i);
}

// The variable i in the aNumber function below is the global variable i that was changed in the for loop above. Its last value was 11, set ju
aNumber (); // 11

setTimeout Variables are Executed in the Global Scope


Note that all functions in setTimeout are executed in the global scope. This is a tricky bit; consider this:

// The use of the "this" object inside the setTimeout function refers to the Window object, not to myObj

var highValue = 200;


var constantVal = 2;
var myObj = {
highValue: 20,
constantVal: 5,
calculateIt: function () {
setTimeout (function () {
console.log(this.constantVal * this.highValue);
}, 2000);
}
}

// The "this" object in the setTimeout function used the global highValue and constantVal variables, because the reference to "this" in the se

myObj.calculateIt(); // 400
// This is an important point to remember.

Do not Pollute the Global Scope


If you want to become a JavaScript master, which you certainly want to do (otherwise you will be watching Honey Boo Boo right now), you have to know that it is
important to avoid creating many variables in the global scope, such as this:

// These two variables are in the global scope and they shouldn't be here
var firstName, lastName;

function fullName () {
console.log ("Full Name: " + firstName + " " + lastName );
}

This is the improved code and the proper way to avoid polluting the global scope

// Declare the variables inside the function where they are local variables

function fullName () {
var firstName = "Michael", lastName = "Jackson";

console.log ("Full Name: " + firstName + " " + lastName );

file:///Users/shafiultareq/Downloads/JavaScript%20is%20Super%20Sexy%20%7C%20JavaScript%20is%20Sexy.html Page 12 of 60
JavaScript is Super Sexy | JavaScript is Sexy 7/22/14, 3:28 PM

In this last example, the function fullName is also in the global scope.

Variable Hoisting
All variable declarations are hoisted (lifted and declared) to the top of the function, if defined in a function, or the top of the global context, if outside a function.

It is important to know that only variable declarations are hoisted to the top, not variable initialization or assignments (when the variable is assigned a value).

Variable Hoisting Example:

function showName () {
console.log ("First Name: " + name);
var name = "Ford";
console.log ("Last Name: " + name);
}

showName ();
// First Name: undefined
// Last Name: Ford

// The reason undefined prints first is because the local variable name was hoisted to the top of the function
// Which means it is this local variable that get calls the first time.
// This is how the code is actually processed by the JavaScript engine:

function showName () {
var name; // name is hoisted (note that is undefined at this point, since the assignment happens below)
console.log ("First Name: " + name); // First Name: undefined

name = "Ford"; // name is assigned a value

// now name is Ford


console.log ("Last Name: " + name); // Last Name: Ford
}

Function Declaration Overrides Variable Declaration When Hoisted


Both function declaration and variable declarations are hoisted to the top of the containing scope. And function declaration takes precedence over variable declarations (but
not over variable assignment). As is noted above, variable assignment is not hoisted, and neither is function assignment. As a reminder, this is a function assignment: var
myFunction = function () {}.
Here is a basic example to demonstrate:

// Both the variable and the function are named myName


var myName;
function myName () {
console.log ("Rich");
}

// The function declaration overrides the variable name


console.log(typeof myName); // function

// But in this example, the variable assignment overrides the function declaration
var myName = "Richard"; // This is the variable assignment (initialization) that overrides the function declaration.

function myName () {
console.log ("Rich");
}

console.log(typeof myName); // string

It is important to note that function expressions, such as the example below, are not hoisted.

var myName = function () {


console.log ("Rich");
}

In strict mode, it is an error if you assign a variable a value without first declaring the variable. It is very good practice to always declare your variables.

Understand JavaScript Closures With Ease


February 2 Last Year

Closures are lovely and reliably serviceable: They allow programmers to program creatively, expressively, and concisely. They are used frequently in JavaScript and, no
matter your JavaScript skill level, you will no doubt encounter them. Sure, closures might appear complex and beyond your scope, but after reading this article, closures
will be much more easily understood and more appealing for usage in your everyday JavaScript programming.

This is a relatively short (and sweet ) post on the details of closures in JavaScript. You should be familiar with JavaScript variable scope before you read further, because
to understand closures you must understand JavaScript’s variable scope.

What is a closure?
A closure is an inner function that has access to the outer (enclosing) function’s variables—scope chain. The closure has three scope chains: it has access to its own scope
(variables defined between its curly brackets), it has access to the outer function’s variables, and it has access to the global variables.

The inner function has access not only to the outer function’s variables, but also to the outer function’s parameters. Note that the inner function cannot call the outer
function’s arguments object, however, even though it can call the outer function’s parameters directly.

You create a closure by adding a function inside another function.


A Basic Example of Closures in JavaScript:

file:///Users/shafiultareq/Downloads/JavaScript%20is%20Super%20Sexy%20%7C%20JavaScript%20is%20Sexy.html Page 13 of 60
JavaScript is Super Sexy | JavaScript is Sexy 7/22/14, 3:28 PM

function showName (firstName, lastName) {


var nameIntro = "Your name is ";
// this inner function has access to the outer function's variables, including the parameter
function makeFullName () {
return nameIntro + firstName + " " + lastName;
}

return makeFullName ();


}

showName ("Michael", "Jackson"); // Your name is Michael Jackson

Closures are used extensively in Node.js; they are workhorses in Node.js’ asynchronous, non-blocking architecture. Closures are also frequently used in jQuery and just
about every piece of JavaScript code you read.
A Classic jQuery Example of Closures:

$(function() {

var selections = [];


$(".niners").click(function() { // this closure has access to the selections variable
selections.push (this.prop("name")); // update the selections variable in the outer function's scope
});

});

Closures’ Rules and Side Effects

1. Closures have access to the outer function’s variable even after the outer function returns:
One of the most important and ticklish features with closures is that the inner function still has access to the outer function’s variables even after the outer function
has returned. Yep, you read that correctly. When functions in JavaScript execute, they use the same scope chain that was in effect when they were created. This
means that even after the outer function has returned, the inner function still has access to the outer function’s variables. Therefore, you can call the inner function
later in your program. This example demonstrates:

function celebrityName (firstName) {


var nameIntro = "This celebrity is ";
// this inner function has access to the outer function's variables, including the parameter
function lastName (theLastName) {
return nameIntro + firstName + " " + theLastName;
}
return lastName;
}

var mjName = celebrityName ("Michael"); // At this juncture, the celebrityName outer function has returned.

// The closure (lastName) is called here after the outer function has returned above
// Yet, the closure still has access to the outer function's variables and parameter
mjName ("Jackson"); // This celebrity is Michael Jackson

2. Closures store references to the outer function’s variables; they do not store the actual value.Closures get more interesting when the value of the outer function’s
variable changes before the closure is called. And this powerful feature can be harnessed in creative ways, such as this private variables example first demonstrated
by Douglas Crockford:
function celebrityID () {
var celebrityID = 999;
// We are returning an object with some inner functions
// All the inner functions have access to the outer function's variables
return {
getID: function () {
// This inner function will return the UPDATED celebrityID variable
// It will return the current value of celebrityID, even after the changeTheID function changes it
return celebrityID;
},
setID: function (theNewID) {
// This inner function will change the outer function's variable anytime
celebrityID = theNewID;
}
}

var mjID = celebrityID (); // At this juncture, the celebrityID outer function has returned.
mjID.getID(); // 999
mjID.setID(567); // Changes the outer function's variable
mjID.getID(); // 567: It returns the updated celebrityId variable

3. Closures Gone Awry


Because closures have access to the updated values of the outer function’s variables, they can also lead to bugs when the outer function’s variable changes with a for
loop. Thus:

// This example is explained in detail below (just after this code box).
function celebrityIDCreator (theCelebrities) {
var i;
var uniqueID = 100;
for (i = 0; i < theCelebrities.length; i++) {
theCelebrities[i]["id"] = function () {
return uniqueID + i;
}
}

return theCelebrities;
}

var actionCelebs = [{name:"Stallone", id:0}, {name:"Cruise", id:0}, {name:"Willis", id:0}];

file:///Users/shafiultareq/Downloads/JavaScript%20is%20Super%20Sexy%20%7C%20JavaScript%20is%20Sexy.html Page 14 of 60
JavaScript is Super Sexy | JavaScript is Sexy 7/22/14, 3:28 PM

var createIdForActionCelebs = celebrityIDCreator (actionCelebs);

var stalloneID = createIdForActionCelebs [0];console.log(stalloneID.id()); // 103

In the preceding example, by the time the anonymous functions are called, the value of i is 3 (the length of the array and then it increments). The number 3 was added
to the uniqueID to create 103 for ALL the celebritiesID. So every position in the returned array get id = 103, instead of the intended 100, 101, 102.

The reason this happened was because, as we have discussed in the previous example, the closure (the anonymous function in this example) has access to the outer
function’s variables by reference, not by value. So just as the previous example showed that we can access the updated variable with the closure, this example
similarly accessed the i variable when it was changed, since the outer function runs the entire for loop and returns the last value of i, which is 103.

To fix this side effect (bug) in closures, you can use an Immediately Invoked Function Expression (IIFE), such as the following:

function celebrityIDCreator (theCelebrities) {


var i;
var uniqueID = 100;
for (i = 0; i < theCelebrities.length; i++) {
theCelebrities[i]["id"] = function (j) { // the j parametric variable is the i passed in on invocation of this IIFE
return function () {
return uniqueID + j; // each iteration of the for loop passes the current value of i into this IIFE and it saves the correct v
} () // BY adding () at the end of this function, we are executing it immediately and returning just the value of uniqueID + j, in
} (i); // immediately invoke the function passing the i variable as a parameter
}

return theCelebrities;
}

var actionCelebs = [{name:"Stallone", id:0}, {name:"Cruise", id:0}, {name:"Willis", id:0}];

var createIdForActionCelebs = celebrityIDCreator (actionCelebs);

var stalloneID = createIdForActionCelebs [0];


console.log(stalloneID.id); // 100

var cruiseID = createIdForActionCelebs [1];console.log(cruiseID.id); // 101

Check back on February 7th for a quiz on JavaScript Closures.

Learn Node.js Completely and with Confidence


February 4 Last Year

Duration: about 2 weeks


Prerequisite: JavaScript knowledge of 5/10

This is the most exciting time to be a JavaScript developer, and it will only get better, particularly because of the advent of HTML5, the abandonment of Flash, the ubiquity
of mobile devices, and most certainly because of Node.js, which allows developers to use JavaScript on the server.

Node.js itself is revolutionary and it is the immediate and near future of modern web application development with JavaScript as the sole server-side language. I provide
you with a detailed roadmap for learning Node.js that has worked for me (an eCommerce Node.js web app I developed), and I am confident it will work for you. You will
learn Node.js completely and you should approach this course with confidence, because you are only 2 to 3 weeks away from building amazingly fast, real-time, modern
web applications in short time.

Why Learn Node.js


JavaScript is the language of the web today and unquestionably for the near future, because there is no alternative to JavaScript on the horizon. The ECMAScript
organization has been moving full pace ahead with advancing the JavaScript language. And Node.js allows developers to develop modern applications with JavaScript as
the sole server-side language.

With a thorough understanding of Node.js, you will be able to develop real-time, fast, scalable, data-driven web applications, and you will have the requisite knowledge to
quickly adapt to any of the emerging, cutting-edge JavaScript frameworks such as Derby.js and Meteor.js.

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.

How Not to Learn Node.js

1. There are countless tutorials on Node.js, but most are not good enough resources for learning Node.js thoroughly, and it is very frustrating to discern which tutorials,
if any, are best for learning Node.js properly. Most of them lack the requisite depth and structure you need to learn Node.js completely.

I read a good bit of Node.js tutorials when I learned Node.js about a year ago. I also wasted a good bit of time on some of the tutorials. Some of them were
disappointing (I didn’t learn anything substantive) and frustratingly unedifying. I will neither name the unhelpful tutorials nor list the links here, but suffice to say,
don’t waste your time following lots of Node.js online tutorials to learn Node.js from the ground up.

I am confident there are some excellent Node.js tutorials, but you have to weed through many mediocre tutorials to find the great ones. It is an inefficient way to
learn Node.js. I did it and I am hopeful this guide will help you, so that you wouldn’t waste as much time as I did.

2. Don’t go to Amazon and choose a Node.js book based on the reviews. Even though this is the customary way to decide on a book (it is how I choose my books),
because Node.js is still a new platform, most of the books don’t have a large enough sample of reviews to provide you with a clear picture of the book’s usefulness
and value. And collectively, the reviews are not great.

If you go to Amazon.com and type “Node.js,” you will see at least 21 Node.js books. While I have only ready 4 of them (the 4 best of the lot), I found a pattern in the
books that were not good: the authors do not appear to have a thorough, vast understanding of the Node.js architecture and platform, and the books appear to be a
collection of mediocre tutorials aggregated for the book.Of the 4 Node.js books I have read, 2 were good, but I recommend only one. The two books were
Professional Node.js: Building JavaScript Based Scalable Software, by Pedro Teixera; and Smashing Node.js: JavaScript Everywhere, by Guillermo Rauch. I
recommend Pedro Teixera’s book, but you can learn quite a bit from Guillermo Rauch’s book, too, so you should get both, if you are very serious about developing
with Node.js

file:///Users/shafiultareq/Downloads/JavaScript%20is%20Super%20Sexy%20%7C%20JavaScript%20is%20Sexy.html Page 15 of 60
JavaScript is Super Sexy | JavaScript is Sexy 7/22/14, 3:28 PM

Book Review
As of this writing,there are only two reviews of Professional Node.js: Building JavaScript Based Scalable Software (Pedro Teixera’s book) on Amazon.com; one of them is
excellent (5 stars) and the other is a bad review–it is best if you read it yourself. This is the bad review of the book:

I have no idea if this book is well written or not because the formatting is so bad as to make it virtually unreadable in some places.

Obviously, the author of this review has not read the book and his review is completely about the formatting, which I have not experienced. I would give the book 5 stars
because it is by far the best Node.js book I have read. But I didn’t buy it on Amazon, so I didn’t review it there.

Also note that I know neither of the authors of the two books I recommend in this article.

Resources

1. Get a copy of The Node Beginner Book by Manuel Kiessling. It is a tiny book: it is really a Node.js tutorial. The book sells in a bundle with another book, Hands-on
Node.js written by the aforementioned Pedro Teixeira, for $9.99. But interestingly, I didn’t find the companion book (by Pedro) to be as useful, so you don’t need it
and we will not use it in our study of Node.js. But since you get both books for $9.99, take the deal and run. Get the Node Beginner Book here:
2. Get a copy of:
— Paperback Version: Professional Node.js: Building Javascript Based Scalable Software , by Pedro Teixera.
— Kindle Version: Professional Node.js: Building Javascript Based Scalable Software , by Pedro Teixera.

Roadmap to Mastering Node.js

1. If you already know JavaScript very well, and you feel invincible when you sit to code in JavaScript, carry on with step 2 below.

If you don’t know JavaScript well enough to develop a full, interactive quiz application with just JavaScript (no jQuery), you should learn JavaScript properly.

If you know enough JavaScript and want to proceed, but you feel you need a JavaScript refresher, read these 3 articles (in the order they are listed):
— JavaScript Objects in Detail
— JavaScript Variable Scope and Hoisting Explained
— (Must Read) Understand JavaScript Closures With Ease

2. Read chapter 1 of Professional Node.js and follow the instructions on how to setup Node.js on your development computer.
3. Read the entire Node Beginner Book. As I noted above, it is a tiny book; basically a tutorial. This tutorial will give you a gentle introduction into Node.js and a very
basic understanding of what Node.js development involves. It is good to start with this before you read the rest of the Professional Node.js book.
4. Read chapter 2 of Professional Node.js.
5. Read the CommonJS section of the article at the link below. You need not read the entire article. Here is a link to just the CommonJS section.
6. Read chapter 3 to 6 of Professional Node.js.
7. Read the entire Part III section (chapter 7 to 15) of Professional Node.js.
8. Optional: If you have got the Smashing Node.js book I referenced earlier, read chapters 8 and 9.
9. Read chapter 17 to 22 of Professional Node.js.
10. And finish up by reading the last 3 chapters of Professional Node.js.
11. Now that you have learned enough Node.js to build the backend of a modern web application, you have to learn Backbone.js so you can rapidly build web
applications on the frontend. You are a Node.js developer if you know only Node.js, but with Backbone.js and Node.js, you are a badass JavaScript developer with
the skills and tools to build all sorts of web applications. Go learn Backbone.js completely.
12. With a complete understanding of Node.js and Backbone.js, you are ready to build any type of web application. You can go ahead and build a startup at this juncture,
if you are intrepid.

But before you head off for your adventure, build the NodeApp web application at the link below; this exercise provides you with a real-world practical in
Node.js/Backbone.js web application development:
http://dailyjs.com/web-app.html

13. Further Learning: There are two more technologies you should learn to help consolidate your Node.js and Backbone.js skills: Handlebars.js for templating and
MongoDB for database. Indeed, you have learned the simple Underscore.js template engine that comes with Backbone.js and you have learned a bit of MongoDB in
step 10 above.

But you have to learn Handlebars because it is more robust and feature rich that the Underscore.js template engine. Read my post, Handlebars.js Tutorial: Learn
Everything About Handlebars.js JavaScript Templating.

And you have to learn more MongoDB to build complex applications. I will have an upcoming post on MongoDB in the coming 5 to 8 days.

Best of luck and stay focused until you complete the entire course: DO NOT GIVE UP. And do not take longer than 3 weeks to complete the course.

Handlebars.js Tutorial: Learn Everything About Handlebars.js JavaScript


Templating
February 18 Last Year

(This is a Handlebars.js Tutorial and a Handlebars.js Reference)

This is a complete tutorial, and indeed a reference, on Handlebars.js templating and, principally, JavaScript templating. Handlebars.js is a client-side (it can be used on the
server, too) templating engine for JavaScript. It is a JavaScript library that you include in your page just as you would include any .js files. And with it, you can add
templates to your HTML page that will be parsed and interpolated (values of properties inserted in place) with the values from the data you passed to the Handlebars.js
function.

How it works: Handlebars.js is a compiler built with JavaScript that takes any HTML and Handlebars expression and compiles them Topics in This Post
to a JavaScript function. This derived JavaScript function then takes one parameter, an object—your data—and it returns a string with When to Use JS Templating and
the HTML and the object properties’ values inserted into the HTML. So, you end up with a string (HTML) that has the values from Why Handlebars.js?

file:///Users/shafiultareq/Downloads/JavaScript%20is%20Super%20Sexy%20%7C%20JavaScript%20is%20Sexy.html Page 16 of 60
JavaScript is Super Sexy | JavaScript is Sexy 7/22/14, 3:28 PM

the object properties inserted in the relevant places, and you insert the string on a page. Handlebars.js Overview

Compare a Non-Handlebars
Do I Have To Use a JavaScript Templating Engine? If so, Why?
Project With a Handlebars.js
Yes. If you develop or plan to develop JavaScript applications, you should use a JavaScript client-side templating engine to keep your Project
JavaScript and HTML sufficiently decoupled, which will allow you to manage your HTML and JS files reliably and easily. Learn Handlebars.js Syntax

Sure, you can use JSDom, or you can fire up server-side templating and send your HTML files via HTTP. But I recommend client- Handlebars.js Built-in Helpers
side templating because it is faster than server-side templating and it provides the easiest way to create and maintain your templates. (Conditionals and Loops)

Handlebars.js Custom Helpers


In addition, just about all the JavaScript front-end frameworks use a JavaScript templating engine, so you will eventually use
JavaScript templating, if you ever use a JavaScript front-end or backend framework. Four Ways to Load/Add
Templates

When to Use JS Templating and Why Handlebars.js? Handlebars.js with Backbone.js,


jQuery, Ember.js, and Meteor.js
There are some specific use cases for JavaScript templating engines.

When To Use a JavaScript Templating Engine?


You should use a JavaScript templating engine like Handlebars.js when:

Whenever you use a JavaScript front-end framework like Backone.js, Ember.js, and the like; most front-end JavaScript frameworks rely on templating engines.
The application’s view (the HTML page or portions of the page) will be updated frequently, especially as a result of changes to the data either from the server via a
REST API or from data on the client
You have multiple tech stacks that depend on your data from the server and you want all the tech stacks to process the same data
Your application has much interactivity and it is very responsive
You are developing a single-page web application with multiple views
You want to easily manage your HTML content; you don’t want your JavaScript code to contain important HTML markup. Here is an example of JS code with
HTML markup (it makes it difficult to manage your HTML markup):
shoesData.forEach (function (eachShoe) {
//Note the intermingling of HTML and JavaScript; it is tedious to follow:
theHTMLListOfShoes += '<li class="shoes">' + '<a href="/' + eachShoe.name.toLowerCase() + '">' + eachShoe.name + ' -- Price: ' + eachShoe.pric
});
return theHTMLListOfShoes;
}

Why Handlebars.js (out of the 8 or more templating engines)?


Unsurprisingly, there are many JavaScript client-side templating engines, but we will focus only on Handlebars.js in this tutorial, since it is the best of the lot. Some of the
other worthy templating engines are Underscore.js’ Template, Mustache.js, EJS, and Dust.js.

Handlebars.js is an extension of the Mustache JavaScript templating language; it supersedes Mustache.js.

Why Use Handlebars.js? Here are some reasons:

Handlebars is one of the most advanced (pre-compiling and the like), feature-rich, and popular of all the JavaScript templating engines, and it has the most active
community.
Handlebars is a logic-less templating engine, which means there is little to no logic in your templates that are on the HTML page. The most important use of
Handlebars, and any templating engine, is to keep your HTML pages simple and clean and decoupled from the logic-based JavaScript files, and Handlebars serves
this purpose well. Indeed, Dust.js is also a logic-less templating engine and a worthy alternative to Handlebars.js.
Moreover, the cutting-edge JavaScript frameworks Meteor.js and Derby.js, which we will cover in upcoming posts, are expected to become mainstream in the
coming months, and both use Handlebars.js. To be clear: Meteor.js uses Handlebars.js and Derby.js “template syntax is largely based on Handlebars” template
syntax. And Ember.js uses Handlebars, too.

While Backbone.js is packaged with Underscore.js templating engine, it is super easy to use Handlebars.js with Backbone.js.

Therefore, the experience and knowledge you will have gained from learning Handlebars.js now will be well worth it, if you use, or plan to use, any of the noted JS
frameworks.

In short, learning Handlebars.js now is an investment and a wise choice: you will program more effectively now and you will adapt easily to the JS frameworks tomorrow
and in the coming weeks and months.

Handlebars.js Overview
Now that we have seen how to use Handlebars in a simple application, let’s study Handlebars in detail.

How Handlebars.js Works?


As noted in the introduction: Handlebars.js is a compiler built with JavaScript that takes any HTML and Handlebars expression and compiles them to a JavaScript function.
This derived JavaScript function then takes one parameter, an object—your data—and it returns an HTML string with the object properties’ values inserted (interpolated)
into the HTML. So, you end up with a string (HTML) that has the values from the object properties inserted in the relevant places, and you insert the string on a page.

This sounds way more complex that it is, so let’s take a closer look.

The 3 Main Parts of Handlebars Templating


To use Handlebars, first you link to the Handlebars.js file in the head block of your HTML page, just like you do for jQuery or any .js files.. Then there are 3 main pieces of
code you use for Handlebars templating:

1. Handlebars.js Expressions
A simple Handlebars expression is written like this (where “content” can be a variable or a helper function with—or without—parameters:

file:///Users/shafiultareq/Downloads/JavaScript%20is%20Super%20Sexy%20%7C%20JavaScript%20is%20Sexy.html Page 17 of 60
JavaScript is Super Sexy | JavaScript is Sexy 7/22/14, 3:28 PM

{{ content }}

Or like this, in the case of Handlebars block expressions (which we will discuss in detail later):

{{#each}}
HTML content and other Handlebars expresion go here.
{{/each}}

Below is a Handlebars expression with HTML. The customerName variable is the property that will be interpolated (its values will be inserted in place) by the
Handlebars.compile function:

<div> Name: {{ customerName }} </div>

The output will be the following (if the customerName variable has the value “Richard”):

Richard

Since you have to pass the Handlebars expression (with any containing HTML) to the Handlebars.compile function, a script tag is used to enclose each Handlebars
template when they are on the HTML page. Indeed, the script tag is not necessary when a template is in its own HTML file, but it is necessary when the Handlebars
template is on the page along with other Handlebars template and other HTML content.

— Script Tag
Handlebars templates are embedded in script tags (where the script tag’s type property is set to “text/x-handlebars-template”). The script tag is similar to the script
tag you normally use to embed JavaScript in the HTML page, except the type attribute is different.You retrieve the HTML content from the script tag and pass it to
the Handlebars compiler.

Here is an example of the Handlebars script tag:

<script id="header" type="text/x-handlebars-template">


<div> Name: {{ headerTitle }} </div>
</script>

2. Data (or Context)


The second piece of code in Handlebars templating is the data you want to display on the page. You pass your data as an object (a regular JavaScript object) to the
Handlebars function. The data object is called the context. And this object can be comprised of arrays, strings, numbers, other objects, or a combination of all of
these.

If the data object has an array of objects, you can use Handlebars each helper (more on helpers later) function to iterate the array, and the current context is set to
each item in the array.

Here are examples of setting up the data object and how to iterate it in a Handlebars template.

— Data object with array of objects

//The customers object has an array of objects that we will pass to Handlebars:
var theData = {customers:[{firstName:”Michael”, lastName:”Alexander”, age:20}, {firstName:”John”, lastName:”Allen”, age:29}]};

You can use the each helper to iterate the customer’s object like this:

<script id="header" type="text/x-handlebars-template">


{{#each customers}} // Note the reference to the customers object
<li> {{ firstName }} {{ lastName }} </li>
{{/each}}
</script>

Or, since we are passing the customer’s object as an array of objects, we can use a block helper (more on block helpers later) statement like this and reference the
customers directly:

<script id="header" type="text/x-handlebars-template">


{{#customers}} // In this example, because the customer’s
<li> {{ firstName }} {{ lastName }} </li>
{{/customers}}
</script>

— Data object with Strings

// In this example, the data object contains properties with strings:


var theData = {headerTitle:"Shop Page", weekDay:”Wednesday”};

<script id="header" type="text/x-handlebars-template">


<div> {{ headerTitle }} </div>
Today is {{weekDay}}
</script>

3. The Handlebars Compile Function


The last piece of code we need for Handlebars templating is actually a two-step execution:
1. Compile the template with the Handlebars.compile function.
2. Then use that compiled function to invoke the data object passed to it (it takes a data object as its sole parameter). And this will return an HTML string with the
interpolated object values inserted into the HTML.

In short:
The Handlebars.compile function takes the template as a parameter and it returns a JavaScript function. We then use this compiled function to execute the data object
and return a string with HTML and the interpolated object values. Then we can insert the string into the HTML page.

Here are the 3 pieces together:


1. On the HTML age: Setup the templates by using Handlebars expressions, and add the templates to a script tag (if using script tags: templates in individual HTML
files don’t need script tags):

file:///Users/shafiultareq/Downloads/JavaScript%20is%20Super%20Sexy%20%7C%20JavaScript%20is%20Sexy.html Page 18 of 60
JavaScript is Super Sexy | JavaScript is Sexy 7/22/14, 3:28 PM

<script id="header" type="text/x-handlebars-template">


<div> {{ headerTitle }} </div>
Today is {{weekDay}}
</script>

2. In the JavaScript file: Initialize the data object

var theData = {headerTitle:"Shop Page", weekDay:”Wednesday”};

// Retrieve the HTML from the script tag we setup in step 1


// We use the id (header) of the script tag to target it on the page
var theTemplateScript = $("#header").html();

3. Also in the JavaScript file: Then we use the Handlebars compile function to compile the templates.
Compile the template retrieved from the script tag:

// The Handlebars.compile function returns a function to theTemplate variable


var theTemplate = Handlebars.compile (theTemplateScript);

Use the theTemplate () function returned by the compile function to generate the final string with interpolated object values. We pass the object data as a parameter.
Then attach the resulting string with HTML to the page:

$(document.body).append (theTemplate (theData));

This will return our HTML with the values from the object inserted in place, and the result will look like this:
__________
Shop Page
Today is Wednesday
__________

Compare a Non-Handlebars Project With a Handlebars.js Project


To get a high-level overview of what development with Handlebars entails when compared with non-JavaScript templating, let’s build a quick, tiny JavaScript
project.

Before we use Handlebars, let’s make use of jQuery and JavaScript without Handlebars, to get a sense of what we are building and how Handlebars will make a
difference.
Without Handlebars, this is what a typical JavaScript/jQuery project will look like when you have content to add to the page with some data. We are simply
displaying a list of shoes and prices .

A Little Non-Handlebars Project


1. Download Handlebars.js and jQuery:
Download the latest version of Handlebars from Github (we are not using it yet, though, but still include it on the page). Get the full version, not the “runtime
only” version (more on the runtime version later): https://github.com/wycats/handlebars.js/downloads

Also, download the latest version of jQuery here (we will use it throughout this tutorial): http://code.jquery.com/jquery-1.9.1.min.js

2. Create a new directory on your computer named “Handlebars_tuts” and place the jQuery and Handlebars.js files in it.

Or, you can open Terminal (on MAC) and change directory to the “Handlebars_tuts” directory. Then type the following commands to download both JS files
directly to the directory with the curl command:

curl http://code.jquery.com/jquery-1.9.1.min.js > jquery-1.9.1.min.js


curl https://github.com/downloads/wycats/handlebars.js/handlebars-1.0.rc.1.min.js > Handlebars.js

3. Make an index.html file and add the following


<html>
<head>
<script type="text/javascript" src="jquery-1.9.1.min.js"></script>
</head>
<body>
The List of Shoes:
<ul class="shoesNav"></ul>
</body>
</html>

4. Create a main.js file and add the following:


Note this JS file has both HTML and JavaScript mixed together in an unhealthy soup

$(function () {

var shoesData = [{name:"Nike", price:199.00 }, {name:"Loafers", price:59.00 }, {name:"Wing Tip", price:259.00 }];

function updateAllShoes(shoes) {
var theHTMLListOfShoes = "";

shoesData.forEach (function (eachShoe) {


// Note the coupling and mixing of HTML and JavaScript; it is tedious to follow
theHTMLListOfShoes += '<li class="shoes">' + '<a href="/' + eachShoe.name.toLowerCase() + '">' + eachShoe.name + ' -- Price: ' + eachSho
});
return theHTMLListOfShoes;
}
$(".shoesNav").append (updateAllShoes(shoesData));

});

file:///Users/shafiultareq/Downloads/JavaScript%20is%20Super%20Sexy%20%7C%20JavaScript%20is%20Sexy.html Page 19 of 60
JavaScript is Super Sexy | JavaScript is Sexy 7/22/14, 3:28 PM

If you open the index.html file in your browser, you should see a simple list with 3 items. This is how we normally develop on the front end without a JavaScript
template engine.

A Little Handlebars Project


Now, lets refactor the code above and use Handlebars.js templating instead of relying on HTML and JavaScript coupled together “unhealthily.”

1. Changes to index.html:
Add this code just below the closing ul tag

<script id="shoe-template" type="x-handlebars-template">


{{#each this}}
<li class="shoes"><a href="/{{name}}">{{name}} -- Price: {{price}} </a></li>
{{/each}}
</script>

2. Changes to main.js:
And here is the refactored JS code that makes use of Handlebars.
Remove all the JS code and replace with the code below
— Note that we have gotten rid of the entire updateAllShoes functions
— And also note there is no HTML in the JS file anymore, all the HTML now live in the HTML file.

$(function () {
var shoesData = [{name:"Nike", price:199.00 }, {name:"Loafers", price:59.00 }, {name:"Wing Tip", price:259.00 }];
//Get the HTML from the template in the script tag
var theTemplateScript = $("#shoe-template").html();

//Compile the template


var theTemplate = Handlebars.compile (theTemplateScript);
$(".shoesNav").append (theTemplate(shoesData));

//We pass the shoesData object to the compiled handleBars function


// The function will insert all the values from the objects in their respective places in the HTML and returned HTML as a string. Then we
});

When you refresh the index.html page in your browser should see the same output we had in the previous non-Handlebars example above.

The preceding illustrate the very basic use of Handlebars.js. As you have seen, using Handlebars allowed us to separate the HTML from the JavaScript. This is
even more important as our application gets more complex; the easier it will be to develop separate template files and manage them effectively. Whereas, the
non-Handlebars example would be a mess to manage as our application gets larger.

That in essence is how using Handlebars.js allows us to keep our HTML files decoupled from our JavaScript files.

The Main Difference Between the Two Projects


This is the main difference between the non-Handlebars.js project and the Handlebars.js project: The non-Handlebars.js project has important HTML markup inside
the JavaScript code, which makes it difficult to manage (create and update) the HTML:

// You can see the HTML and JS intermingled

function updateAllShoes(shoes) {
var theHTMLListOfShoes = "";
shoesData.forEach (function (eachShoe) {
theHTMLListOfShoes += '<li class="shoes">' + '<a href="/' + eachShoe.name.toLowerCase() + '">' + eachShoe.name + ' -- Price: ' + eachShoe.pri
});
return theHTMLListOfShoes;
}
$(".shoesNav").append (updateAllShoes(shoesData));

While the Handlebars.js project’s JavaScript code does not contain the HTML markup (the HTML markup is on the HTML page; only JS is in the JS code):

var theTemplateScript = $("#shoe-template").html();


var theTemplate = Handlebars.compile (theTemplateScript);
$(".shoesNav").append (theTemplate(shoesData));

Learn Handlebars.js Syntax


Handlebars.js Expressions
We saw the Handlebars Expressions above. Handlebars expressions are written like this (a double stash before, followed but the content to be evaluated,
followed a double closing double stash):

<div>{{ content goes here }}

The customerName variable is the property (the expression to be evaluated by the Handlebars compiler) that will be interpolated (its values will be inserted in
place) by the Handlebars compiled function, when it executes:

<div> Name: {{ customerName }} </div>

Comments
This is how you add comments in a Handlebars template:

{{! Whatever is inside this comment expression will not be outputted }}

And you can also use regular HTML comments, but they will be outputted on the HTML page source, as HTML comments of course:

<!-- Regular HTML comments will be in the output -->

Blocks

file:///Users/shafiultareq/Downloads/JavaScript%20is%20Super%20Sexy%20%7C%20JavaScript%20is%20Sexy.html Page 20 of 60
JavaScript is Super Sexy | JavaScript is Sexy 7/22/14, 3:28 PM

Blocks in Handlebars are expression that has a block, an opening {{# }} followed by a closing {{/ }}.

We cover blocks in detail later; this is the syntax for a block:

{{#each}}Content goes here.{{/each}}

Here is an if block

{{#if someValueIsTrue}}Content goes here{{/if}}

The words block and helper are sometimes used interchangeably because most built-in helpers are blocks, although there are function helpers and block
helpers.

Paths (with dot notation)


A path in Handlebars is a property lookup. If we have a name property that contains an object, such as:

var objData = {name: {firstName: "Michael", lastName:"Jackson"}}

We can use nested paths (dot notation) to lookup the property you want, like this:

{{name.firstName}}

Parent Path ../


Handlebars also has a parent path ../ to lookup properties on parents of the current context. Thus:
With a data object such as this:

var shoesData = {groupName:"Celebrities", users:[{name:{firstName:"Mike", lastName:"Alexander" }}, {name:{firstName:"John", lastName:

We can use the parent path ../ to get the groupName property:
<script id="shoe-template" type="x-handlebars-template">
{{#users}}
<li>{{name.firstName}} {{name.lastName}} is in the {{../groupName}} group.</li>
{{/users}}
</script>

The rendered HTML will be:


Mike Alexander is in the Celebrities group.
John Waters is in the Celebrities group.

Context
Handlebars refers to the object you passed to its function as the context. Throughout this article, we use “object data” and sometimes “data” or “object” to refer
to the context object. All these words are used interchangeably from time to time, but you will no doubt understand that we are referring to the object being
passed into the Handlebars function.
Triple Stash {{{ }}} For Non-escape HTML
Ordinarily, you use Handlebars’s double stash {{ }} for expressions, and by default, Handlebars content in this standard double stash is escaped to “protect you
against accidental XSS problems caused by malicious data passed from the server as JSON.” [1]This ensures that nefarious code in the HTML cannot be
injected into the page.But sometimes you want the raw (un-escaped) HTML instead. For this, you can use Handlebars’s triple stash instead {{{ }}}. The triple
stash tag signifies to handlebars to do not escape the HTML content contained in the triple stash.
Partials (sub-templates)
Sometimes you have to render a section of a template within a larger template. You use Partials to do this in Handlebars, and this is the partials expression:

{{> partialName}}

Let’s add a partial template to the basic Handlebars project we built earlier. We will add color and size under each shoe.

Changes to main.js
1. Replace the existing data object with the following (we are adding properties for color and size):

var shoesData = {allShoes:[{name:"Nike", price:199.00, color:"black", size:10 }, {name:"Loafers", price:59.00, color:"blue", size:9 }, {n

2. Add the following just before the line with the jQuery append method:

Handlebars.registerPartial("description", $("#shoe-description").html());

Changes to index.html:
1. Replace the shoe-template template with this:

<script id="shoe-template" type="x-handlebars-template">


{{#each allShoes}}
<li class="shoes">
<span class="shoe-name"> {{name}} - </span> price: {{price}}
{{> description}}
</li>
{{/each}}
</script>

2. Add this new template for the description; add it just below the shoe-template:

<script id="shoe-description" type="x-handlebars-template">


<ul>
<li>{{color}}</li>
<li>{{size}}</li>
</ul>
</script>

The Final HTML should show color and size under each shoe list item.

file:///Users/shafiultareq/Downloads/JavaScript%20is%20Super%20Sexy%20%7C%20JavaScript%20is%20Sexy.html Page 21 of 60
JavaScript is Super Sexy | JavaScript is Sexy 7/22/14, 3:28 PM

That is how you add a partial- (or sub-template) to the main template.

Handlebars.js Built-in Helpers (Conditionals and Loops)

As we have learned earlier, Handlebars is a logic-less (little to no logic embedded in the templates) templating engine. But there must be a way for us to execute
complex logic when using the templates. Handlebars provides this functionality with what are called Helpers, which are the conditional and loops for executing
simple logic.

They are logic expressions and logic blocks that provide the necessary logic for templates on the HTML page. You can add complex functionality with your own
custom helpers, which we will discuss in a bit.

Built-in Helpers
The built-in helpers (conditionals and loops) are:

Each Helper: {{#each}}


We saw the each helper earlier. It allows you to iterate over an array or object provided in the data object (the context). For example, if you have an array of
items you would like to list on the page, you can do this:
First we setup the data

var favoriteFruits = {allFruits:["Tangerine", "Mango", "Banana"]};

Then we use the each block inside the script tag.


Note that this is referring to the allFruits property—each item in its array
<script id="fruits-template" type="x-handlebars-template">
List of fruits:
{{#each allFruits}}
<li>{{this}} </li>
{{/each}}
</script>

This will result in the following HTML

<li> Tangerine </li>


<li> Mango </li>
<li> Banana </li>

Also, if the data object passed to the each helper is not an array, the entire object is the current context and we use the this keyword. This illustrates:
If the data looks like this:

var favoriteFruits = {firstName:"Peter", lastName:"Paul"};

As opposed to this:

var favoriteFruits = {customers: {firstName:"Peter", lastName:"Paul"}};

We use the this keyword as demonstrated here:

Since the evaluated expression from the data will be just the object, we use the this keyword:

{{#each this}}
<li>{{firstName}} {{lastName}} </li>
{{/each}}

— Nested Properties with the Each helper


Let’s use the nested properties (that we learned earlier) with the each helper:

var favoriteFruits = {allFruits:[{fruitName:"Tangerine", naitiveTo:[{country:"Venezuela"}]},{fruitName:"Mango"}] };

{{#each allFruits}}
<li>{{fruitName}} {{naitiveTo.0.country}} </li>
{{/each}}

If Helper: {{#if}}
The if helper works just like a regular if statement, except it does not accept any conditional logic. It checks for truthy values such as true, any non-empty or
non null value, and the like. The block is only rendered if the if evaluates to a truthy value.
— Here are some examples:
We check to see if the userActive property is truthy. If it is, the block is rendered:

<div class="user-data">
{{#if userActive}}
Welcome, {{firstName}}
{{/if}}
</div>

As one of the Handlebars developers advised: it is best to check for the length property of the variable, to catch cases where an array might be empty:

<div class="user-data">
{{#if userActive.length}}
Welcome, {{firstName}}
{{/if}}
</div>

As noted above, the if helper does not evaluate conditional logic, so we cannot do this:

file:///Users/shafiultareq/Downloads/JavaScript%20is%20Super%20Sexy%20%7C%20JavaScript%20is%20Sexy.html Page 22 of 60
JavaScript is Super Sexy | JavaScript is Sexy 7/22/14, 3:28 PM

<div class="user-score">
{{#if userScore > 10 }}
Congratulations, {{firstName}}, You did it.
{{/if}}
</div>

We have to use a custom helper (we discuss this shortly) to add such conditional logic

Else: {{else}}
The else section (note that it is not a block on its own) is rather simple, since it is a section of a block. It can be used with the if block or any other block. The
content in the else section is only rendered if expression evaluates to falsy.

We check to see if the userLoggedIn property is truthy. If it is not, the content in the else block will be rendered:

<div class="user-data">
{{#if userLoggedIn}}
Welcome, {{firstName}}
{{else}}
Please Log in.
{{/if}}
</div>

Unless Helper: {{#unless}}


As an alternative to the else helper, you use the unless block helper. The content between the unless block only renders if the unless expression evaluates to a
falsy value. So this is best used if you only want to check for falsy values:

We replace the if block and the else section above with just the unless block, to render the content only if the property evaluates to a falsy value.

This expression reads: only render the contents in the block if the userLoggedIn property evaluates to false

<div class="user-data">
{{#unless userLoggedIn}}
Please Log in.
{{/unless}}
</div>

With Helper: {{#with}}


The with helper allows us to target a specific property of the object. For example, we know that the object is always the current context in a Handlebars
template, as we have learned in a few sections earlier. But if you want to target a different property from the current context, you can use the with helper, just
as you can use the parent path (../) to do this.Let’s see the with helper in action:

If we have a context object such as:

var shoesData = {groupName:"Celebrities", celebrity:{firstName:"Mike", lastName:"Alexander" } };

We can use the with block to target the groupName property where we need access to its values:

<script id="shoe-template" type="x-handlebars-template">


{{groupName}} Group
{{#with celebrity}}
<li>{{firstName}} {{lastName}}</li>
{{/with}}
</script>

And this is the rendered HTML:


Celebrities Group
– Mike Alexander

The with block is probably one that you will rarely use.

Handlebars.js Custom Helpers

(very important and versatile)


In addition to the built-in helpers we just discussed, Handlebars allows us to add our own custom helpers, and this is even more important than the built-in helpers,
since we can add any kind of complex logic to the custom helpers. We can even re-create the built-in helpers with our own custom helpers, though this would be a
waste of time.

With custom helpers, we can add any kind or JavaScript logic. We register the custom helper before all the rest of the Handlebars JS code. Custom helpers are
created in the JavaScript code, not inside the Handlebars template.

There are two types of custom helpers you can create: a custom function helper is simply a helper that does not use a block, and a custom block helper is a helper
with a block.

Custom Function Helpers


Let’s make a simply custom function helper that executes some conditional logic, since we could not use conditional logic with the built-in helpers.

The data object:

var contextObj = {score:85, userName:"Mike"};

First, we have to register the custom helper with Handlebars.registerHelper method. This method takes a string (the name of the helper) as the first parameter and a
function with any number of parameters as the second parameter.

Handlebars.registerHelper ("theNameOfTheHelper", function (theScore) {


console.log("Grade: " + theScore );
var userGrade = "C";

file:///Users/shafiultareq/Downloads/JavaScript%20is%20Super%20Sexy%20%7C%20JavaScript%20is%20Sexy.html Page 23 of 60
JavaScript is Super Sexy | JavaScript is Sexy 7/22/14, 3:28 PM

if (theScore >= 90) {


return "A" ;
}
else if (theScore >= 80 && theScore < 90) {
return "B" ;
}
else if (theScore >= 70 && theScore < 80) {
return "C" ;
}
else {
return "D" ;
}

});

Here is the Handlebars template that uses the custom function helper we just created:

<script id="shoe-template" type="x-handlebars-template">


{{theNameOfTheHelper score}}
</script>

The output on the HTML page is:


B

Custom Block Helpers


In addition to custom function helpers, we can also add custom block helpers. When we register a custom block helper, Handlebars automatically adds an options
object as the last parameter in the callback function. And the options object has an fn method, a hash object, and an inverse method.

The options.fn method:


The fn method takes an object (your data) as a parameter that it uses as the context inside the custom helper block template. You can pass any data object, or if you
want to use the same data context referenced in the template, you can use this.

An example will better illustrate. This is the data object we are using (we will sum all the scores in the array and replace the score array with the total of the scores:

var contextObj = [{firstName: "Kapil", lastName:"Manish", score:[22, 34, 45, 67]}, {firstName: "Bruce", lastName:"Kasparov", score:[10, 34

Here we setup the template with the userScore block helper, which we define below:

<script id="shoe-template" type="x-handlebars-template">


{{#userScore this}}
<div>{{firstName}} {{lastName}}, Your Total Score is <strong>{{score}}</strong> </div>
{{/userScore}}
</script>

We register the userScore block helper with Handlebars.registerHelper.


Note the last item in the parameter is the options object, which Handlebars inserts automatically, and we use it here:

Handlebars.registerHelper ("userScore", function (dataObject, options) {


var templateWithInterpolatedData = "";

for (var i = dataObject.length - 1; i >= 0; i--) {


//Sum user scores from the score array and replace the array with the total
dataObject[i].score = dataObject[i].score.reduce(function (prev, cur, index, array) {
return prev + cur;
});

// Each object in the data object array is interpolated with the options.fn method, which processes all the HTML from the template and insert

// Just so you understand the purpose of the options.fn method: it does exactly what the regular handlebars template function does when we pas

// Without the options.fn object in this example, the raw objects (instead of the interpolated values) would have been returned

templateWithInterpolatedData += options.fn (dataObject[i]);

// We return the full string of HTML with all the values from the data object inserted into place.

return templateWithInterpolatedData;
});

And this is the HTML output:


​Bruce Kasparov, Your Total Score is 201
Kapil Manish, Your Total Score is 168

— It is also important to know that a custom block helper can be inserted anywhere in the template, and we can pass any number of parameters in the template for
the custom block helper.

The options.inverse method:


The inverse method is used as the else section of any block statement. So, you would use options.fn to return when the expression in the callback evaluates to a truthy
value. But you would use options.inverse when the expression evaluates to falsy (to render content in the else part of the block).

The options.hash object:


Handlebars expressions take not only strings and variables as arguments, but you can pass key-value pairs separated by spaces as well.
For example:
(Note there is no comma separating the key-value pairs arguments.)

{{#myNewHelper score=30 firstName="Jhonny" lastName="Marco"}}


Show your HTML content here.

file:///Users/shafiultareq/Downloads/JavaScript%20is%20Super%20Sexy%20%7C%20JavaScript%20is%20Sexy.html Page 24 of 60
JavaScript is Super Sexy | JavaScript is Sexy 7/22/14, 3:28 PM

{{/myNewHelper}}

And that invocation of the Handlebars expression with the key-value pairs as parameters will be added automatically onto the hash object in the helper callback
function. Thus:

Handlebars.registerHelper ("myNewHelper", function (dataObject, options) {


//JSON.stringify used to serialize the object (to a string)
console.log(JSON.stringify (options.hash));
//The output is: {score:30, firstName:"Jhonny", lastName:"Marco"}
});

Four Ways to Load/Add Templates


There are four main ways you can add your Handlebars.js templates to your pages:

1. Use Script Tags


The first and simplest, indeed, the least desirable, way to add the Handlebars template to the page is by adding the script tag, as we have done throughout this
tutorial so far. You add the entire script tag with the template, like the example below, on the HTML page:

<script id="shoe-template" type="x-handlebars-template">


{{#userScore this}}
<div>{{firstName}} {{lastName}}, Your Total Score is <strong>{{score}}</strong> </div>
{{/userScore}}
</script>

Pros

Quick to setup and use, if you have a very simple application or page
Little to no ramp-up time (time to learn and implement is negligible).

Cons

All the templates are on the page in script tags, which becomes a nightmare to maintain if you have many templates.
It can be problematic to manage memory effectively in medium to large applications, since all the templates are always on the page and you cannot
easily add and remove them, for example in a single-page web application.
It is difficult to create highly-responsive interfaces with these static templates that have a full life cycle in the application.
The templates cannot be precompiled. Precompiled templates are executed considerably faster than templates that have to be compiled in the browser
before being rendered. Compiling templates is the most expensive operation for JavaScript templating engines. So the inability to precompile the
templates would result in avoidable latency in your application.
2. Use Custom Function
You can place all of your templates in HTML files (without the script tag) and load them and compile in one go. Then you can add the compiled templates to
the page whenever they are needed.

A StackOverflow user, koorchik, has created a custom function to handle the loading and the compiling of templates in a concise manner. It is below.

Pros

All the templates can be kept in separate HTML files, which allows for easy maintenance.
No ramp-up time to learn and implement the function: after studying the function for a bit, you will understand it and will be ready to use it in a few
minutes.
The function is very lightweight.
It is versatile, because it facilitates the use of both precompiled templates and templates that haven’t been compiled; and you can even pass preloaded
templates to the function.

Con

None as yet :), but feel free to suggest any in the comments below.

The Custom Function

// And this is the definition of the custom function


function render(tmpl_name, tmpl_data) {
if ( !render.tmpl_cache ) {
render.tmpl_cache = {};
}

if ( ! render.tmpl_cache[tmpl_name] ) {
var tmpl_dir = '/static/templates';
var tmpl_url = tmpl_dir + '/' + tmpl_name + '.html';

var tmpl_string;
$.ajax({
url: tmpl_url,
method: 'GET',
async: false,
success: function(data) {
tmpl_string = data;
}
});

render.tmpl_cache[tmpl_name] = _.template(tmpl_string);
}

return render.tmpl_cache[tmpl_name](tmpl_data);
}

file:///Users/shafiultareq/Downloads/JavaScript%20is%20Super%20Sexy%20%7C%20JavaScript%20is%20Sexy.html Page 25 of 60
JavaScript is Super Sexy | JavaScript is Sexy 7/22/14, 3:28 PM

This is how you would use the custom function to load a mytemplate.html file; pass a data object as second parameter

var rendered_html = render('mytemplate', {});

3. Use AMD and Require.js


AMD is a specification that outlines a mechanism for loading modules and their dependencies asynchronously. We will leave the particulars of the AMD
specification for another article.

For the purpose of this Handlebars templating, the bottom line is that we use a define () function to register our modules and dependencies (including
templates) and Require.js ( a file and module loader) will load our templates so we can assign them to a variable and use them in our project. More on AMD
and Requires.js in the Backbone.js application later.

Pros

With the AMD module mechanism, your code will be well organized.
You can easily and dynamically load templates in a structured manner.
You can keep all the templates in separate HTML files for easy maintenance.
Different developers can edit or create different HTML template files.
Require.js can concantenate all JS files into one file JS file, thus reducing the number of HTTP requests and download time for the application.

Con

Steep Ramp-up time: AMD and Require.js have a moderate to steep learning curve, and you might likely have to learn Backbone.js or another JS
framework that utilize these technologies in an abstracted manner.

Handlebars template with AMD and Require.js Example


The templates are in separate HTML files, and they don’t need the script tag anymore, so the user_account.html file looks like this:

// The define function is part of the AMD mechanism for loading


define([
'jquery',
'underscore',
'handlebars',
// Require.js text plugin loads the HTML template pages
'text!templates/user_account.html',
'text!templates/user_profile.html'],
function ($, _, Backbone, HandleBars,
UserAccount_Template, UserProfile_Template) {

// These are the two objects we will be using


userAccountDataObject: {accountNumber:85444, balance: $120.00},
userProfileDataObject: {firstName:”Michael, lastName:”Harrington”},

// Compile the Handlebars template that we loaded in (the user_account.html and user_profile.html) and assign them to the following two v
userAccount_compiledTemplate:
HandleBars.compile(UserAccount_Template),
userProfile_compiledTemplate:
HandleBars.compile(UserProfile_Template),

// This function will add the Handlebars compiled templates on the page
render: function () {
// Use the compiled function (userAccount_compiledTemplate) and pass to it the context (the data object). The result will be the HTML fro

this.$(".user-account-div").html
(this.userAccount_compiledTemplate(userAccountDataObject);

// Ditto for this template function


this.$(".user-profile-div").html
(this.userProfile_compiledTemplate(userProfileDataObject);
});

4. Precompile The Templates


With the script tag and the AMD/Requires.js methods of adding the templates to the page, Handlebars has to compile the templates on the client side, and this
is the most expensive operation for JavaScript Template engines.

To reduce latency and speed up page execution, Handlebars has a node.js module that precompiles your templates. And because the templates are precompiled,
the execution time is considerably faster and you only include a runtime Handlebars.js file on the page.

I do not include an example code to show how to precompile Handlebars template, because the code will be best understood within the context of a complete
application, and we will build a complete application with Backbone.js and precompile the Handlebars template in part 2 of this post.

Pros

Because the precompiled template files are in JavaScript, they can be minified and combined into one JavaScript file for the entire application, including
all the libraries and other JS files. This will significantly reduce the number of HTTP requests to the server on startup, and thus reduce the download time
for the application.
The application will execute considerably faster, because the expensive compile operation has been completed.
All the advantages with the AMD/Require.js option, if used with AMD and Require.js.

Cons

The Handlebars precompile script is a Node.js module, which means you need to have Node.js installed on your development machine to precompile the
templates.
Since all the templates files are now JavaScript files, the templates cannot easily be edited on the server, to make quick changes.
Making changes to files is a two-step process: You change the HTML files, then you have to run the precompile step to compile the templates to
JavaScript. However, this last step can be enhanced with watch folders that automatically notices changes to the templates files in the template folder,
and precompile the templates immediately.

file:///Users/shafiultareq/Downloads/JavaScript%20is%20Super%20Sexy%20%7C%20JavaScript%20is%20Sexy.html Page 26 of 60
JavaScript is Super Sexy | JavaScript is Sexy 7/22/14, 3:28 PM

Handlebars.js with Backbone.js, jQuery, Ember.js, and Meteor.js


Part 2 (coming soon)
In a follow-up post, we get to use Handlebars.js with some of the most popular JavaScript frameworks. We will build 4 quiz applications with 4 different frameworks
(jQuery, Ember.js, Backbone.js, and Meteor.js), and we will use Handlebars in all the applications. Furthermore, we will load the templates in each of the 4 different
ways described above.

Try Handlebars Online in your Browser


The website at the link below has a useful utility that you can use to try Handlebars online in your browser.
Here is the link:
http://tryhandlebarsjs.com/

References
1. http://handlebarsjs.com/

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
Topics in This Post
once all the powerful tips are ready.
Powerful JavaScript Idiomatic
I provide you with 12 simple, yet powerful, JavaScript tips and detailed explanation of each. These are techniques that all JavaScript Expressions With && and ||
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 Powerful Uses of Immediately
developer, if you aren’t already one. Invoked Function Expressions

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:

function documentTitle(theTitle)
if (!theTitle) {
theTitle = "Untitled Document";
}
}

Use this:

function documentTitle(theTitle)
theTitle = theTitle || "Untitled Document";
}

Explanation:
— First, read the “Important Note” box below for a refresher on JavaScript’s Falsy and Truthy values
— The || operator first evaluates the expression on the left, if it is truthy, it returns that value. If it is falsy, it evaluates and returns the value of the right operand (the
expression on the right).
— If theTitle variable is falsy, the expression on the right will be returned and assigned to the variable. On the other hand, if theTitle is truthy, its value will be
returned and assigned to the variable.

JavaScript Falsy Values: null, false, 0 undefined, NaN, and “” (this last item is an empty string).
— Note that Infinity, which is a special number like NaN, is truthy; it is not falsy, while NaN is falsy.

JavaScript Truthy Values: Anything other than the falsy values.

Example 2: Basic short circuting with && (Logical AND)


Instead of this:

function isAdult(age) {
if (age && age > 17) {
return true;
}
else {
return false;
}
}

Use this:

function isAdult(age) {
return age && age > 17 ;
}

file:///Users/shafiultareq/Downloads/JavaScript%20is%20Super%20Sexy%20%7C%20JavaScript%20is%20Sexy.html Page 27 of 60
JavaScript is Super Sexy | JavaScript is Sexy 7/22/14, 3:28 PM

Explanation:
— The && operator first evaluates the expression on the left. If it is falsy, false is returned; it does not bother to evaluate the right operand.
— If the the first expression is truthy, also evaluate the right operand (the expression on the right) and return the result.

It Gets More Exciting!


Example 3:
Instead of this:

if (userName) {
logIn (userName);
}
else {
signUp ();
}

Use this:

userName && logIn (userName) || signUp ();

Explanation:
— If userName is truthy, then call the logIn function with userName as the parameter.
— If userName is falsy, call the signUp function

Example 4:
Instead of this:

var userID;
if (userName && userName.loggedIn) {
userID = userName.id;
}
else {
userID = null;
}

Use this:

var userID = userName && userName.loggedIn && userName.id

Explanation:
— If userName is truthy, call userName.loggedIn and check if it is truthy; if it is truthy, then get the id from userName.
— If userName is falsy, return null.

2. Powerful Uses of Immediately Invoked Function Expressions


(How Immediately Invoked Function Expressions Work and When to Use Them)
IIFE (pronounced “Iffy”) is an abbreviation for Immediately Invoked Function Expression, and the syntax looks like this:

(function () {
// Do fun stuff
}
)()

It is an anonymous function expression that is immediately invoked, and it has some particularly important uses in JavaScript.

How Immediately Invoked Function Expressions Work?


The pair of parenthesis surrounding the anonymous function turns the anonymous function into a function expression or variable expression. So instead of a
simple anonymous function in the global scope, or wherever it was defined, we now have an unnamed function expression.

It is as if we have this:
// Shown without the parentheses here:
? = function () {};

// And with the parentheses here:


(? = function () {});
// An unknown variable assigned the value of a function, wrapped in a parentheses, which turns it into an unnamed function expression.

Similarly, we can even create a named, immediately invoked function expression:

(showName = function (name) {console.log(name || "No Name")}) (); // No Name

showName ("Rich"); // Rich


showName (); // No Name

— Note that you cannot use the var keyword inside the opening pair of parentheses (you will get a syntax error), but it is not necessary in this context to use
var since any variable declared without the var keyword will be a global variable anyway.
— We were able to call this named function expression both immediately and later because it has a name.
— But we can’t call the anonymous function expression later, since there is no way to refer to it. This is the reason it is only useful when it is immediately
invoked.

By placing the anonymous function in parentheses (a group context), the entire group is evaluated and the value returned. The returned value is actually the
entire anonymous function itself, so all we have to do is add two parentheses after it to invoke it.
Therefore, the last two parentheses tell the JS compiler to invoke (call) this anonymous function immediately, hence the name “Immediately Invoked Function
Expression.”
Because JavaScript has function-level scope, all the variables declared in this anonymous function are local variables and therefore cannot be accessed outside

file:///Users/shafiultareq/Downloads/JavaScript%20is%20Super%20Sexy%20%7C%20JavaScript%20is%20Sexy.html Page 28 of 60
JavaScript is Super Sexy | JavaScript is Sexy 7/22/14, 3:28 PM

the anonymous function.


So we now have a powerful piece of anonymous code inside an unnamed function expression, and the code is meaningless unless we invoke the anonymous
function, because nothing can access the code. It is the immediate invocation of the anonymous function that makes it powerful and useful.
You can pass parameters to the anonymous function, just like you would any function, including variables. The anonymous function’s scope extend into any
outer function that contains it and to the global scope. Read my article, JavaScript Variable Scope and Hoisting Explained, for more.

When To Use Immediately Invoked Function Expressions?


1. To Avoid Polluting the Global Scope
The most popular use of the IIFE is to avoid declaring variables in the global scope. Many JavaScript libraries use this technique, and of course many JS pros,
too. It is especially popular amongst jQuery plugin developers. And you should use an IIFE in the top-level (main.js) of your applications.

In this first example, I am using it in the global scope to keep all my variables local to the anonymous function, and thus outside the global scope where
variables can shadow (block) other already-defined variables with the same name (probably from an included library or framework). All of my code for the
application will start in the IIFE:

// All the code is wrapped in the IIFE


(function () {
var firstName = “Richard”;
function init () {
doStuff (firstName);
// code to start the application
}

function doStuff () {
// Do stuff here
}

function doMoreStuff () {
// Do more stuff here
}

// Start the application


init ();
}) ();

— Note that you can also pass jQuery or any other object or variable via the parameter (the last 2 parentheses).

2. Use With the Conditional Operator


The use of the IIFE in this manner is not as well known, but it quite powerful since you can execute complex logic without having to setup and call a named
function:

— Note the two anonymous functions in the conditional statement


— Why would you do this? Because it is powerful and badass.
— I purposely added enough space between each section so the code can read better.
var unnamedDocs = [], namedDocs = ["a_bridge_runover", "great_dreamers"];

function createDoc(documentTitle) {
var documentName = documentTitle

(function (theName) {
var newNamedDoc = theName.toLocaleLowerCase().replace(" ", "_");
namedDocs.push(newNamedDoc);

return newNamedDoc;
})(documentTitle)

(function () {
var newUnnamedDoc = "untitled_" + Number(namedDocs.length + 1);
unnamedDocs.push(newUnnamedDoc);
return newUnnamedDoc;
})();

return documentName;
}
createDoc("Over The Rainbow"); // over_the rainbow
createDoc(); // untitled_4

3. Use it in Closures to Prevent Fold Over


I discussed this particular use of the IIFE before in my post, Understand JavaScript Closures With Ease. So I will copy the section of that code and reuse it
here.

To prevent close over in for loops, we can use an Immediately Invoked Function Expression to prevent a common bug when closures are used with for loops:

To fix side effects (bug) in closures, you can use an IIFE, such as if this example:

function celebrityIDCreator (theCelebrities) {


var i;
var uniqueID = 100;
for (i = 0; i < theCelebrities.length; i++) {
theCelebrities[i]["id"] = function (j) { // the j parametric variable is the i passed in on invocation of this IIFE

file:///Users/shafiultareq/Downloads/JavaScript%20is%20Super%20Sexy%20%7C%20JavaScript%20is%20Sexy.html Page 29 of 60
JavaScript is Super Sexy | JavaScript is Sexy 7/22/14, 3:28 PM

return function () {
return uniqueID + j; // each iteration of the for loop passes the current value of i into this IIFE and it saves the corr
}
} (i); // immediately invoke the function passing the i variable as a parameter
}

return theCelebrities;
}

var actionCelebs = [{name:"Stallone", id:0}, {name:"Cruise", id:0}, {name:"Willis", id:0}];

var createIdForActionCelebs = celebrityIDCreator (actionCelebs);

var stalloneID = createIdForActionCelebs [0];


console.log(stalloneID.id()); // 100

var cruiseID = createIdForActionCelebs [1];console.log(cruiseID.id()); // 101

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 Topics in This Post
beginner to attainment. How NOT To Learn JavaScript

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 Resources For This Course
websites and web applications (including an internet startup), you need to know JavaScript. And while there are more than enough Weeks 1 and 2 (Introduction,
online resources to teach you JavaScript, finding the most efficient and beneficial method to learn the “language of the web” is not Data Types, Expressions, and
easy and could be frustrating. Operators

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, Weeks 3 and 4 (Objects, Arrays,
Java, Python, or Perl) to develop scalable, dynamic, database-driven web applications, today you can do as much and more with Functions, DOM, jQuery)
JavaScript alone.
Get The Ultimate JavaScript
Editor: WebStorm

Your First Project—A Dynamic


How NOT To Learn JavaScript Quiz

Do not try to learn JavaScript the first time from bits of unrelated or related JavaScript tutorials Weeks 5 and 6 (Regular
online—this is the worst way to learn a programming language. It could work for some after countless such Expressions, Window Object,
tutorials, but it is an inefficient process that lacks the proper hierarchical structure needed for learning Events, jQuery)
a subject matter thoroughly. And this could lead to your being stuck quite frequently, when you start to
Weeks 7 and, if necessary 8
build websites and web applications with the language. In short, you will not have the know-how you need to
(Classes, Inheritance, more
use that language as a tool—as your tool.
HTML5)
In addition, some will recommend you learn JavaScript from “JavaScript: The Good Parts,” by the
venerable JavaScript godfather Douglas Crockford. While Mr. Crockford, who is immensely knowledgeable in Continue Improving
JavaScript, is seen as the Einstein of the JavaScript world, his book, The Good Parts, is not a
Words of Encouragement
good JavaScript book for beginners. It does not explain JavaScript’s core concepts in a thorough, clear,
easily digestible form. I do recommend you follow Crockford’s advanced videos, however, as part of the Advanced roadmap.
And do not try to learn the language by using only Codecademy, because while you will know how to program
bits of very small JavaScript tasks, you absolutely will not have learned enough to build a
web applications. I do recommend Codecademy below as a supplemental learning resource, however.

Resources For This Course


UPDATE: A study group was just created (on April 8) for this roadmap on Reddit by Reddit user d0gsbody. He and the members of the group are very helpful and
motivated. I recommend you join the group; they will keep you motivated and help you on your way to learning JavaScript. It is difficult to learn JavaScript from scratch
on your own. Here is the link: Learning JS Properly – Study Group on Reddit.

We are using either of two JavaScript books, one is ideal for first-time programmers and the other is better if you have at least a bit programming experience.

You can use either of the following two books:

This first book is my personal preference because the author explains the topics very well and it covers up to advanced JavaScript topics. However, it is best used if
you have at least some very basic understanding of web development. Therefore, if you have at least a bit of programming or web development experience (it needn’t
be in JavaScript), buy this book:
— The paperback Version: Professional JavaScript for Web Developers
— The Kindle Version: Professional JavaScript for Web Developers

Or:

file:///Users/shafiultareq/Downloads/JavaScript%20is%20Super%20Sexy%20%7C%20JavaScript%20is%20Sexy.html Page 30 of 60
JavaScript is Super Sexy | JavaScript is Sexy 7/22/14, 3:28 PM

Buy this book if you have no programming experience:


— The paperback Version: JavaScript: The Definitive Guide
— The Kindle Version: JavaScript: The Definitive Guide

Sign up for an account on Stack Overflow (a FREE service). It is a forum for asking and answering programming questions. This website will be considerably more
useful than Codecademy for answering your programming questions, even very basic, seemingly stupid (remember, there is never a stupid question) questions.
Sign up for an account on Codecademy. This is an online platform to learn to program: you write code on their website, right in your browser. (It is also a FREE
service).
JavaScriptIsSexy Blog Posts on Objects, Closures, Variable Scope and Hoisting, Functions, and more.

The Roadmap to JavaScript Attainment


You will learn just about the full JavaScript language (and jQuery and some HTML5) in 6 to 8 weeks,
if you complete this entire course outline. If you don’t have enough time to commit to do all the sections in 6
weeks (which is a relatively aggressive schedule), try to do it in no more than 8 weeks. The longer you take, the
harder it will be for you to grasp and remember everything you learn.

Weeks 1 and 2 (Introduction, Data Types, Expressions, and Operators


1. If you do not already know HTML and CSS very well, complete the Web Fundamentals Track on Codecademy.
2. Read the Preface and Chapters 1 and 2 of JavaScript: The Definitive Guide.

Or Read the Introduction and Chapters 1 and 2 of Professional JavaScript for Web Developers.

3. Very Important: Every example code you encounter in the book, type it out and test it and tweak it (experiment with it) in Firefox’s or Chrome’s browser console.
Or use JSFiddle. Don’t use Safari. I recommend Firefox—add the Firebug Add on to firefox and use it for testing and debugging your code. The browser console is
an area of the browser where you can write and run JavaScript code.

And JSFiddle is a web application that allows you to write and test your code online, right in your browser. You can test all sorts of code, including a combination of
HTML, CSS, and JavaScript (and jQuery).

4. Work through the Introduction to JavaScript section of the JavaScript Track on Codecademy.
5. Read chapters 3 and 4 of JavaScript: The Definitive Guide.

Or Read the Preface and Chapters 3 and 4 of Professional JavaScript for Web Developers. You can skip the section on “Bitwise Operators”; it is hardly likely you
will use those in your JavaScript career.

And again, make sure you stop and write the example code in your browser’s console (or JSFiddle) and experiment—change some of the variables and tweak the
code a bit.

6. Read chapter 5 of JavaScript: The Definitive Guide. No reading for Professional JavaScript for Web Developers, you have learned the material already in the last
chapter.
7. And work through sections 2 to 5 of the JavaScript Track on Codecademy.

Weeks 3 and 4 (Objects, Arrays, Functions, DOM, jQuery)


1. Read my post JavaScript Objects in Detail

Or read chapter 6 of JavaScript: The Definitive Guide.

Or read chapter 6 of Professional JavaScript for Web Developers. NOTE: Only read the “Understanding Objects” section.

Any of the 3 is fine, although the 2 textbooks go into more detail: the extra detail you can skip confidently, if you read and thoroughly understand my post.

2. Read chapters 7 and 8 of JavaScript: The Definitive Guide

Or read chapters 5 and 7 of Professional JavaScript for Web Developers

3. At this juncture, you should be spending a lot of time writing code in your browser’s console and testing if-else statements, for loops, Arrays, Functions, Objects, and
more. It is critically important that you know (and keep practicing) how to code independently (without help from Codecademy) in your browser. By the time you get
back to Codecademy, you shouldn’t need any help or hints. Every assignment should be easy for you.

If you are still struggling with Codecademy, go back to your browser and keep hacking away. This is where you will learn the most. This is analogous to Lebron
James honing his skills as a youth in the “streets” (the neighborhood basketball courts), or to Bill Gates hacking away in his basement.

There is tremendous value in your hacking away and learning bit by bit on your own. You have to see the value in this strategy, and you have to embrace it and trust
that it will work.

False Sense of Accomplishment When Using Codecademy


The biggest problem with Codecademy is that the hints and little code snippets help you so much that you have a false sense of accomplishment when you are
progressing through the exercises easily. You wouldn’t know it at the time, but much of what you are doing is not on your own.

Now, Codecademy is still great for helping you to learn how to code, particularly in the manner in which it guides you through the process of developing small
projects and small applications from very basic code constructs like if statements, for loops, functions, and variables.

4. Return to Codecademy and complete the JavaScript track by working through sections 6, 7, and 8 (Data Structures to Object 2).
5. While you are on Codecademy, go ahead and build the 5 little Basic Projects on the Projects track. After this, you are done with Codecademy. And this is a good
thing, because the more you work on your own, the faster you will learn and the better prepared you will be to start programming on your own.
6. Read chapters 13, 15, 16, and 19 of JavaScript: The Definitive Guide.

Or read chapters 8, 9, 10, 11, 13, and 14 of Professional JavaScript for Web Developers. This book does not cover jQuery, and the jQuery coverage on Codecademy
is insufficient. Follow this jQuery course—it is free: http://try.jquery.com/

file:///Users/shafiultareq/Downloads/JavaScript%20is%20Super%20Sexy%20%7C%20JavaScript%20is%20Sexy.html Page 31 of 60
JavaScript is Super Sexy | JavaScript is Sexy 7/22/14, 3:28 PM

And you can read chapter 19 of JavaScript: The Definitive Guide, if you have the book, for more on jQuery.

7. Work through the entire jQuery course at http://try.jquery.com/

Get The Ultimate JavaScript Editor: WebStorm


Before you build your first project, if you plan to be a JavaScript developer or use JavaScript often, you should take a break now and download a trial copy of
WebStorm. Learn how to get started with WebStorm here (written especially for this course).

WebStorm is unquestionably the absolute best editor (IDE) for programming JavaScript. It costs $49.00 when your 30-day trial period expires, but it is probably the
best investment you will make as a JavaScript developer, besides buying the book you are using in this course and learning JavaScript.

Make sure you set WebStorm to use JSHint. JSHint is a “tool to detect errors and potential problems in JavaScript code and to enforce your team’s coding
conventions.” The cool thing with using WebStorm is that JSHint automatically adds a red line under errors in your code, just as a spell checker does in a word
processing application. So JSHint will show you all the errors in your code (including HTML errors) and make you a better JavaScript programmer, even as you are
learning. This is extremely important. You will thank me later after you realize how much WebStorm and JSHint have helped you become a better programmer.
Moreover, WebStorm is a world-class, professional-grade IDE for coding professional JavaScript web applications, so you will use it a lot. And it integrates Node.js,
Git, and other JavaScript frameworks, so even after you have become a rock star JavaScript developer, you will be using it, unless a more compelling JavaScript IDE
comes out in the next few months.
It is fair that I also mention Sublime Text 2, which is the next best JavaScript editor. But it is not as feature rich and complete (even with numerous add-on packages)
as WebStorm. I use Sublime Text 2 to make small edits to files of different programming languages, including JS files. But I don’t use it to program full JavaScript
web applications.

Your First Project—A Dynamic Quiz


At this juncture, you have learned enough to build a solid web application that is manageable. Don’t proceed any further until you can successfully build this application I
describe below. If you are stuck, ask questions on Stack Overflow and reread sections of the book to properly understand the concepts.

You are building a JavaScript quiz application (you will use HTML and CSS as well) that will function as follows:

It is a simple quiz that has radio button choices, and it will show the user her score upon completion.
The quiz can show any number of questions and any number of choices.
Tally the user’s score and display the final score on the last page. The last page will only show the score, so remove the last question.
Use an array to store all the questions. Each question, along with its choices and correct answer, should be stored in an object. The array of questions should look
similar to this:
// Only one question is in this array, but you will add all the questions.
var allQuestions = [{question: "Who is Prime Minister of the United Kingdom?", choices: ["David Cameron", "Gordon Brown", "Winston Churchill"

Dynamically (with document.getElementById or jQuery) add the next question and remove the current question from the screen, when the user clicks the “Next”
button. The Next button will be the only button to navigate this version of the quiz.
You can ask for help in the comments below or preferably on Stack Overflow. You are likely to get a prompt and accurate answer on Stack Overflow.

Weeks 5 and 6 (Regular Expressions, Window Object, Events, jQuery)


1. Read chapters 10, 14, 17, and 20 of JavaScript: The Definitive Guide.

Or read chapters 20 and 23 of Professional JavaScript for Web Developers.

2. Remember to keep typing out all the example codes in Firefox console and tweak each piece of code to experiment with it to really understand how it works and
what it does.
3. At this point, you should be very comfortable with JavaScript, probably feeling like a Jedi. You are not quite a Jedi yet, you must keep using your newly acquired
knowledge and skills as often as possible to keep learning and improving.
4. Improve Your Quiz Application From Earlier:
— Add client-side data validation: make sure the user answers each question before proceeding to the next question.
— Add a “Back” button to allow the user to go back and change her answer. The user can go back up to the first question. For the questions that the user has
answered already, be sure to show the radio button selected, so that the user is not forced to answer the questions again, which she has completed.
— Use jQuery to add animation (fade out the current question and fade in the next question).
— Test the quiz on IE 8 and 9, and fix any bugs. This will give you a good workout
— Store the quiz questions in an external JSON file.
— Add user authentication: allow users log in, and save their login credentials to local storage (HTML5 browser storage).
— Use cookies to remember the user, and show a “Welcome, First Name” message when the user returns to the quiz.

Weeks 7 and, if necessary 8 (Classes, Inheritance, more HTML5)


1. Read chapters 9, 18, 21, and 22 of JavaScript the Definitive Guide.

Or read my blog post, OOP In JavaScript: What You NEED to Know.

Or read chapters 6 (only the “Object Creation” and “Inheritance” sections this time) 16, 22, and 24 of Professional JavaScript for Web Developers. NOTE: The
reading in this section of the book is the most technical reading you will encounter in this entire roadmap. It is up to you if you want to read all of it. You should at
least learn the Prototype Pattern, Factory Pattern, and Prototypal Inheritance. You don’t have to know all the other patterns.

2. Improve Your Quiz Application Even Further:


— Use Twitter Bootstrap for the entire page layout, including the quiz elements to make it look more professional. As an added bonus, use the tabs user interface
component from Twitter Bootstrap and show 4 different quizzes, one on each tab.
— Learn Handlebars.js and add Handlebars.js templating to the quiz. You should no longer have any HTML in your JavaScript code. Your quiz is getting more
advanced bit by bit.
— Keep a record of all the users who take the quiz and show each user how her score ranks amongst the scores from other quiz takers.
3. Later (after you have learned Backbone.js and Node.js), you will use these two technologies to refactor your quiz code and turn the same quiz into a sophisticated,

file:///Users/shafiultareq/Downloads/JavaScript%20is%20Super%20Sexy%20%7C%20JavaScript%20is%20Sexy.html Page 32 of 60
JavaScript is Super Sexy | JavaScript is Sexy 7/22/14, 3:28 PM

single-page, modern web application built with the latest JavaScript frameworks. And you will store the users’ authentication credentials and scores in a MongoDB
database.
4. Next: Decide on a personal project to build, and start building your project promptly (while everything is fresh in your mind). Use JavaScript the Definitive Guide (or
“Professional JavaScript for Web Developers,” if you own it) as a reference when you are stuck. And of course be an active member of Stack Overflow: ask
questions and answer other programmers’ questions.

Continue Improving
1. Learn Backbone.js Completely
2. Learn Intermediate and Advanced JavaScript
3. Learn Node.js Completely and With Confidence
4. Read my forthcoming post on Getting Started with Meteor.js
5. Read my forthcoming posts on the Three Best Front-end JavaScript Frameworks

Words of Encouragement
All the best with your studies. Never give up! When you are struggling and you are feeling dumb (you may from time to time), always remember that many (probably
most) other new and, even experienced, programmers around the world are probably feeling the same way.

It is difficult in the beginning when you are learning to code for the first time, especially if you are pass your teenage years. Teenagers have no fear and nothing to lose, and
much time to waste use on whatever they are passionate about. So challenges may appear as only brief roadblocks to them.

But after your teenager years, you want results fast because you don’t have sufficient time to kill on figuring out seemingly trivial matters for many, many hours. But this is
where you have to dig in deep and don’t get frustrated; just carry on and stick with the task or finding the bug until you figure it out, for a worthwhile reward is awaiting
you when you triumph in the end—programming is fun and lucrative.

The joy and intense pleasure one gets from building an application is an awesome feeling that must be experienced to be understood. Even more satisfying, however, is the
empowerment you experience when you realize you have attained the skill and knowledge to build applications from scratch.

There will come the moment when you realize that all the difficulty you endured was well worth it, because you became a programmer and you know your future is very
bright as a JavaScript developer. Just like the thousands upon thousands before you: You survived the toughest bugs, you survived giving in and giving up, and you
triumphed over finding many excuses to quit.

Feel free to share your links with us when you build something, even if it is a tiny, itsy-bitsy project

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 Topics in This Post
free you from the constrains of using the limited JS techniques you have been using to develop JS applications, and they will give you What Topics Compose
new insights and new techniques—a Jedi’s temperament and stature—to program JS applications with ease, efficiency, and “Intermediate and Advanced
preciseness. JavaScript”?

If you are new to JavaScript and you are an experienced programmer in another langauge such as Java, Python, ActionScript, Rails, Why Should I Learn Advanced
and PHP, it is important that you learn JavaScript properly. JavaScript has many idiosyncracies and uncommon concepts that you JavaScript?
must know well before you follow this Intermediate to Advanced JavaScript course. Resources For This Course

Get WebStorm, If You Don’t


What Topics Compose “Intermediate and Advanced JavaScript”? Have It

Intermediate and Advanced JavaScript topics include: Week 1 (Essential JavaScript


— Debugging JS in the browser, Object-oriented JavaScript Techniques)
— Advanced Functions: Callback functions, Bind, Curry, IIFE (Immediately Invoked Function Expression) Week 2 (Complete JavaScript
— Asynchronous execution, timers, Prototypal Inheritance, and Closures Jedi Training)
— JavaScript Design Patterns, Object Creation Patterns, and Code Reuse Patterns
— Code Minification and Compression, Loading Strategies, and Dependency Management Further Reading

Final Words
Why Should I Learn Advanced JavaScript?
If you work as a font-end developer or you plan to develop JavaScript applications, libraries, or frameworks, it is essential that you understand the aforementioned
advanced JavaScript topics, because you will not be able to develop complex JavaScript applications without knowing them.

file:///Users/shafiultareq/Downloads/JavaScript%20is%20Super%20Sexy%20%7C%20JavaScript%20is%20Sexy.html Page 33 of 60
JavaScript is Super Sexy | JavaScript is Sexy 7/22/14, 3:28 PM

Moreover, when you are familiar with all the best JavaScript techniques, even if you don’t remember how to use them, you can easily look them up and use them in
powerful ways to make your application run faster, load faster, use less code, reuse code, and perform optimally. Overall, you will use JavaScript as a Jedi would a
lightsaber—you will easily vanquish every JS challenge with ease , eliminate bugs with relish, and execute tasks in an instant, compared with your previous
apprentice self

Resources For This Course


We are using 2 books; fear not, both books are short reads. So the reading is relatively light; we can carry on with our weekly customs as we study advanced JavaScript in 2
weeks. Here are the books we are using (the 2 books will cost just under $30):

This first one is available in paperback on Amazon:


Effective JavaScript: 68 Specific Ways to Harness the Power of JavaScript . This is my favorite JavaScript book.

As noted in the comments by Erica, you can also get the “eBook format (epub, mobi, and pdf) on the Informit website at this link:
http://www.informit.com/store/effective-javascript-68-specific-ways-to-harness-the-9780321812186

And this one:


Preferably the eBook (Kindle):
JavaScript Patterns

Or in Paperback: JavaScript Patterns

The Roadmap to Advanced JavaScript


You will learn just about all the JavaScript advanced techniques and details about JavaScript’s most important concepts that you will use often as a JavaScript Developer.

If you don’t have enough time to commit to read the books in 2 weeks, try to do it in no more than 3 weeks. The longer you take, the harder it will be for you to grasp and
remember everything you will learn.

Get WebStorm, If You Don’t Have It


If you plan to be a JavaScript developer or use JavaScript often, you should take a break now and download a trial copy of WebStorm.

It is unquestionably the best editor (IDE) for programming JavaScript. It costs $49.00 when your 30-day trial period expires, but it is probably the best investment
you will make as a JavaScript developer, besides buying the books you are using in this course and learning advanced JavaScript.
Make sure you set WebStorm to use JSHint. JSHint is “tool to detect errors and potential problems in JavaScript code and to enforce your team’s coding
conventions.”[1].
Moreover, WebStorm is a world-class, professional-grade IDE for coding professional JavaScript web applications, so you will use it a lot. And it integrates Node.js,
Git, and other JavaScript frameworks, so even after you have become a rock star JavaScript developer, you will be using it, unless a more compelling JavaScript IDE
comes out in the next few months.
I should also mention Sublime Text 2, which is the next best JavaScript editor. But it is not as feature rich and complete (even with numerous add-on packages) as
WebStorm. I use Sublime Text 2 to make small edits to files of different programming languages, including JS files. But I don’t use it to program full JavaScript web
applications.

Week 1 (Essential JavaScript Techniques)


1. Read the entire Effective JavaScript book.
This is my favorite JavaScript book. Every page is packed with incredible tips and insightful techniques. I kept whispering, “A Ha,” on many pages.

It provides you with 68 excellent JavaScript techniques and concepts that you need to know as a JavaScript developer.

2. While reading the book, practice the concepts in WebStorm or your browser’s console to reinforce and completely understand the topics through hands-on practice.
Simply trying to memorize everything you have learned without practicing is a great way to ensure you will forget them and never completely understand them.

Week 2 (Complete JavaScript Jedi Training)


1. Since we are trained JavaScript apprentices, we needn’t develop an application while learning the advanced JavaScript techniques. We only have to know and
understand all the advanced techniques, so we can whip them out and use them or look them up and use them, when the need arises.

Read the entire JavaScript Patterns book.

2. Optional: Since there are a few hours to spare this week, you should have enough time to watch Douglas Crockford’s Advanced JavaScript Videos. They are not too
lengthy.

Further Reading
The following books provide additional advanced topics that you should know well if you do indeed want to be a an advanced JavaScript developer. Why come 90% of
way, take it home the last 10% with the following books.

For Techniques in Developing Faster JavaScript Web Applications:


Read High Performance JavaScript (Build Faster Web Application Interfaces) .
Learn About Testing Your JavaScript Applications:
Buy
Kindle Version: Test-Driven JavaScript Development

Or the Paperback Version: Test-Driven JavaScript Development

If You Are Developing JavaScript Libraries and Frameworks:


Read Secrets of the JavaScript Ninja by jQuery creator John Resig.

file:///Users/shafiultareq/Downloads/JavaScript%20is%20Super%20Sexy%20%7C%20JavaScript%20is%20Sexy.html Page 34 of 60
JavaScript is Super Sexy | JavaScript is Sexy 7/22/14, 3:28 PM

Final Words
JavaScript is a fun and lovable programming language, and with it, you will be able to quickly develop sophisticated web applications that hundreds of millions of users
can use within hours of completion. There is much satisfaction from being a JavaScript developer, and indeed much pleasure. Share some of your newly acquired advanced
JavaScript skills with others and be a good steward for advancing the web and creating applications that users love.

To become an advanced JS programmer you need to combine real-world programming experience at all levels and in various forms (developing disparate applications with
myriad technologies, libraries and frameworks), and implementation of the advanced techniques learned. So it is imperative that you put the skills and techniques you have
learned from this course into practice—when you are developing web applications.

Have fun developing and keep coming back, for there is still much for you to learn on JavaScriptIsSexy.com ;).

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 Topics in This Post
everything about callback functions. Callback functions are probably the most widely used functional programming technique in What is a Callback or Higher-
JavaScript, and they are literally in just about every piece of JavaScript and jQuery code, yet they are a mystery to many JavaScript order Function?
developers. You will know how to use them after reading this article.
How Callback Functions Work?
Callback functions are derived from a programming paradigm called functional programming. At a simple and fundamental level, Basic Principles When
functional programming is the use of functions as arguments. Functional programming was—and still is, though to a much lesser Implementing Callback
extent today—seen as an esoteric technique of specially trained, master programmers. Functions

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

Final Words
What is a Callback or Higher-order Function?
A callback function, also known as a higher-order function, is a function that is passed to another function (let’s call this other function “otherFunction”) as a parameter,
and the callback function is called (executed) inside otherFunction. A callback function is essentially a pattern (an established solution to a common problem), and
therefore, the use of a callback function is also known as a callback pattern.

Here is a simple, common use of a callback function in jQuery:

//Note that the item in the click method's parameter is a function, not a variable.
//The item is a callback function
$("#btn_1").click(function() {
alert("Btn 1 Clicked");
});

As you can see in the preceding example, we pass a function as a parameter to the click method. And the click method will call (or execute) the callback function we
passed to it. This is a typical use of callback functions in JavaScript, and indeed it it widely used in jQuery.

Here is another classic example of callback functions from basic JavaScript:

var friends = ["Mike", "Stacy", "Andy", "Rick"];

friends.forEach(function (eachName, index){


console.log(index + 1 + ". " + eachName); // 1. Mike, 2. Stacy, 3. Andy, 4. Rick
});

Again, note the way we pass an anonymous function (a function without a name) to the forEach method as a parameter.

So far, we have passed anonymous functions as parameter to other functions or methods. Lets now understand how callbacks work before we look at more concrete
examples and start making our own callback functions.

How Callback Functions Work?


Because functions are first-class objects in JavaScript, we can treat functions like objects, so we can pass functions around like variables and return them in functions and
use them in other functions. When we pass a callback function as an argument to another function, we are only passing the function definition. We are not executing the
function in the parameter. We aren’t passing the function with the trailing pair of executing parenthesis () like we do when we are executing a function.

And since the containing function has the callback function in its parameter as a function definition, it can execute the callback anytime. This allows us to execute the
callback functions at any point in the containing function.

It is important to note that the callback function is not executed immediately. It is “called back” (hence the name) at some specified point inside the containing function’s
body. So, even though the first jQuery example looked like this:

//The anonymous function is not being executed there in the parameter.


//The item is a callback function
$("#btn_1").click(function() {
alert("Btn 1 Clicked");

file:///Users/shafiultareq/Downloads/JavaScript%20is%20Super%20Sexy%20%7C%20JavaScript%20is%20Sexy.html Page 35 of 60
JavaScript is Super Sexy | JavaScript is Sexy 7/22/14, 3:28 PM

});

The anonymous function will be called later inside the function body. Even without a name, it can still be accessed later via the arguments object by the containing
function.

Callback Functions Are Closures


When we pass a callback function as an argument to another function, the callback is executed at some point inside the containing function’s body just as if the callback
was defined in the containing function. This means the callback is essentially a closure. Read my detailed post, Understand JavaScript Closures With Ease for more on
closures.

As we know, closures have access to the containing function’s scope, so the callback function can access the containing functions variables, and even the variables from the
global scope.

Basic Principles When Implementing Callback Functions


Callback functions are uncomplicated, but there are some basic principles when implementing callback functions that we should be familiar with before we start making
and using our own callback functions.

Use Named OR Anonymous Functions as Callbacks


In the earlier jQuery and forEach examples of callback functions above, we used anonymous functions that were defined in the parameter of the containing function. That is
one of the common patterns of using callback functions. Another popular pattern of using callback function is to declare a named function and pass the name of that
function to the parameter.
Thus:

// global variable
var allUserData = [];

// generic logStuff function that prints to console


function logStuff (userData) {
if ( typeof userData === "string")
{
console.log(userData);
}
else if ( typeof userData === "object")
{
for (var item in userData) {
console.log(item + ": " + userData[item]);
}

// A function that takes two parameters, the last one a callback function
function getInput (options, callback) {
allUserData.push (options);
callback (options);

// When we call the getInput function, we pass logStuff as a parameter.


// So logStuff will be the function that will called back (or executed) inside the getInput function
getInput ({name:"Rich", speciality:"JavaScript"}, logStuff);
// name: Rich
// speciality: JavaScript

Pass Parameters to Callback Functions


Since the callback function is just a normal function when it is executed, we can pass parameters to it. We can pass any of the containing function’s properties (or global
properties) as parameters to the callback function. In the preceding example, we pass options as a parameter to the callback function. Let’s pass a global variable and a local
variable:

//Global variable
var generalLastName = "Clinton";

function getInput (options, callback) {


allUserData.push (options);
// Pass the global variable generalLastName to the callback function
callback (generalLastName, options);
}

Make Sure Callback is a Function Before Executing It


It is always wise to check that the callback function passed in the parameter is indeed a function before calling it. Also, it is good practice to make the callback function
optional.

Let’s refactor the getInput function from the previous example to ensure these checks are in place.

function getInput(options, callback) {


allUserData.push(options);

// Make sure the callback is a function


if (typeof callback === "function") {
// Call it, since we have confirmed it is callable
callback(options);
}
}

Without the check in place, if the getInput function is called either without the callback function as a parameter or in place of a function a non-function is passed, our code
will result in a runtime error.

Problem When Using Methods With The this Object as Callbacks

file:///Users/shafiultareq/Downloads/JavaScript%20is%20Super%20Sexy%20%7C%20JavaScript%20is%20Sexy.html Page 36 of 60
JavaScript is Super Sexy | JavaScript is Sexy 7/22/14, 3:28 PM

When the callback function is a method that uses the this object, we have to modify how we execute the callback function to preserve the this object context. Or else the
this object will either point to the global window object (in the browser), if callback was passed to a global function. Or it will point to the object of the containing method.
Let’s explore this in code:

// Define an object with some properties and a method


// We will later pass the method as a callback function to another function
var clientData = {
id: 094545,
fullName: "Not Set",
// setUserName is a method on the clientData object
setUserName: function (firstName, lastName) {
// this refers to the fullName property in this object
this.fullName = firstName + " " + lastName;
}
}

function getUserInput(firstName, lastName, callback) {


// Do other stuff to validate firstName/lastName here

// Now save the names


callback (firstName, lastName);
}

In the following code example, when clientData.setUserName is executed, this.fullName will not set the fullName property on the clientData object. Instead, it will set
fullName on the window object, since getUserInput is a global function. This happens because the this object in the global function points to the window object.

getUserInput ("Barack", "Obama", clientData.setUserName);

console.log (clientData.fullName);// Not Set

// The fullName property was initialized on the window object


console.log (window.fullName); // Barack Obama

Use the Call or Apply Function To Preserve this


We can fix the preceding problem by using the Call or Apply function (we will discuss these in a full blog post later). For now, know that every function in JavaScript has
two methods: Call and Apply. And these methods are used to set the this object inside the function and to pass arguments to the functions.

Call takes the value to be used as the this object inside the function as the first parameter, and the remaining arguments to be passed to the function are passed individually
(separated by commas of course). The Apply function’s first parameter is also the value to be used as the this object inside the function, while the last parameter is an array
of values (or the arguments object) to pass to the function.

This sounds complex, but lets see how easy it is to use Apply or Call. To fix the problem in the previous example, we will use the Apply function thus:

//Note that we have added an extra parameter for the callback object, called "callbackObj"
function getUserInput(firstName, lastName, callback, callbackObj) {
// Do other stuff to validate name here

// The use of the Apply function below will set the this object to be callbackObj
callback.apply (callbackObj, [firstName, lastName]);
}

With the Apply function setting the this object correctly, we can now correctly execute the callback and have it set the fullName property correctly on the clientData object:

// We pass the clientData.setUserName method and the clientData object as parameters. The clientData object will be used by the Apply function to s
getUserInput ("Barack", "Obama", clientData.setUserName, clientData);

// the fullName property on the clientData was correctly set


console.log (clientData.fullName); // Barack Obama

We would have also used the Call function, but in this case we used the Apply function.

Multiple Callback Functions Allowed


We can pass more than one callback functions into the parameter of a function, just like we can pass more than one variable. Here is a classic example with jQuery’s AJAX
function:

function successCallback() {
// Do stuff before send
}

function successCallback() {
// Do stuff if success message received
}

function completeCallback() {
// Do stuff upon completion
}

function errorCallback() {
// Do stuff if error received
}

$.ajax({
url:"http://fiddle.jshell.net/favicon.png",
success:successCallback,
complete:completeCallback,
error:errorCallback

});

“Callback Hell” Problem And Solution


In asynchronous code execution, which is simply execution of code in any order, sometimes it is common to have numerous levels of callback functions to the extent that

file:///Users/shafiultareq/Downloads/JavaScript%20is%20Super%20Sexy%20%7C%20JavaScript%20is%20Sexy.html Page 37 of 60
JavaScript is Super Sexy | JavaScript is Sexy 7/22/14, 3:28 PM

you have code that looks like the following. The messy code below is called callback hell because of the difficulty of following the code due to the many callbacks. I took
this example from the node-mongodb-native, a MongoDB driver for Node.js. [2]. The example code below is just for demonstration:

var p_client = new Db('integration_tests_20', new Server("127.0.0.1", 27017, {}), {'pk':CustomPKFactory});


p_client.open(function(err, p_client) {
p_client.dropDatabase(function(err, done) {
p_client.createCollection('test_custom_key', function(err, collection) {
collection.insert({'a':1}, function(err, docs) {
collection.find({'_id':new ObjectID("aaaaaaaaaaaa")}, function(err, cursor) {
cursor.toArray(function(err, items) {
test.assertEquals(1, items.length);

// Let's close the db


p_client.close();
});
});
});
});
});
});

You are not likely to encounter this problem often in your code, but when you do—and you will from time to time—here are two solutions to this problem. [3]

1. Name your functions and declare them and pass just the name of the function as the callback, instead of defining an anonymous function in the parameter of the main
function.
2. Modularity: Separate your code into modules, so you can export a section of code that does a particular job. Then you can import that module into your larger
application.

Make Your Own Callback Functions


Now that you completely (I think you do; if not it is a quick reread :)) understand everything about JavaScript callback functions and you have seen that using callback
functions are rather simple yet powerful, you should look at your own code for opportunities to use callback functions, for they will allow you to:

Not repeat code (DRY—Do Not Repeat Yourself)


Implement better abstraction where you can have more generic functions that are versatile (can handle all sorts of functionalities)
Have better maintainability
Have more readable code
Have more specialized functions.

It is rather easy to make your own callback functions. In the following example, I could have created one function to do all the work: retrieve the user data, create a generic
poem with the data, and greet the user. This would have been a messy function with much if/else statements and, even still, it would have been very limited and incapable
of carrying out other functionalities the application might need with the user data.

Instead, I left the implementation for added functionality up to the callback functions, so that the main function that retrieves the user data can perform virtually any task
with the user data by simply passing the user’s full name and gender as parameters to the callback function and then executing the callback function.

In short, the getUserInput function is versatile: it can execute all sorts of callback functions with myriad of functionalities.

// First, setup the generic poem creator function; it will be the callback function in the getUserInput function below.
function genericPoemMaker(name, gender) {
console.log(name + " is finer than fine wine.");
console.log("Altruistic and noble for the modern time.");
console.log("Always admirably adorned with the latest style.");
console.log("A " + gender + " of unfortunate tragedies who still manages a perpetual smile");
}

//The callback, which is the last item in the parameter, will be our genericPoemMaker function we defined above.
function getUserInput(firstName, lastName, gender, callback) {
var fullName = firstName + " " + lastName;

// Make sure the callback is a function


if (typeof callback === "function") {
// Execute the callback function and pass the parameters to it
callback(fullName, gender);
}
}

Call the getUserInput function and pass the genericPoemMaker function as a callback:

getUserInput("Michael", "Fassbender", "Man", genericPoemMaker);


// Output
/* Michael Fassbender is finer than fine wine.
Altruistic and noble for the modern time.
Always admirably adorned with the latest style.
A Man of unfortunate tragedies who still manages a perpetual smile.
*/

Because the getUserInput function is only handling the retrieving of data, we can pass any callback to it. For example, we can pass a greetUser function like this:

function greetUser(customerName, sex) {


var salutation = sex && sex === "Man" ? "Mr." : "Ms.";
console.log("Hello, " + salutation + " " + customerName);
}

// Pass the greetUser function as a callback to getUserInput


getUserInput("Bill", "Gates", "Man", greetUser);

// And this is the output


Hello, Mr. Bill Gates

file:///Users/shafiultareq/Downloads/JavaScript%20is%20Super%20Sexy%20%7C%20JavaScript%20is%20Sexy.html Page 38 of 60
JavaScript is Super Sexy | JavaScript is Sexy 7/22/14, 3:28 PM

We called the same getUserInput function as we did before, but this time it performed a completely different task.

As you can see, callback functions are fantastic. And even though the preceding example is relatively simple, imagine how much work you can save yourself and how well
abstracted your code will be, if you start using callback functions. Go for it.

Here are common ways callback functions are frequently used in JavaScript programming, especially in modern web application development and in libraries and
frameworks:

For asynchronous execution (such as reading files, and making HTTP requests)
In Event Listeners/Handlers
In setTimeout and setInterval methods
For Generalization: code conciseness

Final Words
JavaScript callback functions are wonderful and powerful to use and they provide great benefits to your web applications and to your code. You should use them when the
need arises; look for ways to refactor your code for Abstraction, Maintainability, and Readability with callback functions.

See you next time, and remember to keep coming back, because JavaScriptIsSexy.com has much to teach you and you have much to learn.

References
1. http://c2.com/cgi/wiki?FirstClass
2. https://github.com/mongodb/node-mongodb-native
3. http://callbackhell.com/
4. JavaScript Patterns by Stoyan Stefanov (Sep 28, 2010)

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

Object Oriented Programming (OOP) refers to using Classes (Functions in JavaScript) to create objects, which are self-contained pieces of code. Then we use those objects
as building blocks for our applications. Using objects in this manner allows us to adopt some valuable techniques, including Inheritance (objects can inherit features from
other objects), Polymorphism (objects can share the same interface—how they are accessed and used—while their underlying implementation of the interface may differ),
and Encapsulation (each object is responsible for specific tasks).

In this article, we are only concerned with Inheritance and Encapsulation, since only these are applicable for OOP in JavaScript. Essentially, in JavaScript, objects can
encapsulate functionalities and inherit methods and properties from other objects.

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

OOP in JavaScript
Encapsulation and Inheritance Overview Encapsulation in JavaScript

Objects can be thought of as the main actors in an application, or simply the main “things” or building blocks that do all the work. As Inheritance in JavaScript
you know by now, objects are everywhere in JavaScript, and we use object literals or constructor Functions to create objects. Also, it Final Words
is important to know that Functions are objects in JavaScript.

Encapsulation refers to enclosing all the functionalities of an object within that object, so that the object’s internal workings (its
methods and properties) are hidden from the rest of the application. This allows us to abstract or localize specific set of functionalities on objects.

Inheritance refers to an object being able to inherit methods and properties from a parent object (a Class in other OOP languages, or a Function in JavaScript).

Both of these concepts, encapsulation and inheritance, are important because they allow us to build applications with reusable code, scalable architecture, and abstraction.
The result is applications that are easy to maintain, efficient, and scalable.

An instance is an implementation of a Function. In simple terms, it is a copy (or “child”) of a Function or object. For example:

function Tree (typeOfTree) {} // Tree is a constructor function, because we will use new keyword to invoke it.

var bananaTree = new Tree ("banana"); // bananaTree is an instance of Tree.

In the preceding example code, bananaTree is an object that was created from the Tree constructor function. We say that the bananaTree object is an instance of the Tree
object. Tree is both an object and a function, because functions are objects in JavaScript. bananaTree can have its own methods and properties and inherit methods and
properties from the Tree object, as we will discuss in detail when we study inheritance below.

OOP in JavaScript
The two important principles with OOP in JavaScript are Object Creation patterns (Encapsulation) and Code Reuse patterns (Inheritance). When building applications,
you create many objects, and there are many ways of creating these objects: you can use the very basic object literal pattern, for example:

var myObj = {name:"Richard", profession:"Developer"};

file:///Users/shafiultareq/Downloads/JavaScript%20is%20Super%20Sexy%20%7C%20JavaScript%20is%20Sexy.html Page 39 of 60
JavaScript is Super Sexy | JavaScript is Sexy 7/22/14, 3:28 PM

Or you can use a constructor function (Classes in other languages, but Functions in JavaScript). For example:

function People (name, profession) {} //People () is the constructor function, because we use the new keyword below to invoke it.

var richard = new People (“Richard”, “Developer”) // richard is a new object we create from the People () constructor function.

In the latter example, we use a custom constructor function to create an object. This is how we create objects when we want to add methods and properties on our objects,
and when we want to encapsulate functionality on our objects. JavaScript developers have invented many patterns (or ways) for creating objects with constructor functions.
And when we say Object Creation Patterns, we are concerned principally with the many ways of creating objects from constructor functions, as in the preceding example.

In addition to the patterns for creating objects, you want to reuse code efficiently. When you create your objects, you will likely want some of them to inherit (have similar
functionality) methods and properties from a parent object, yet they should be able to also have their own methods and properties. Code reuse patterns facilitate ways in
which we can implement inheritance.

These two universal principles—creating objects (especially from constructor Functions) and allowing objects to inherit properties and methods—are the main focus of this
article and, indeed, the main concepts with OOP in JavaScript. We first discuss the object creation pattern.

Encapsulation in JavaScript
(The Best Object Creation Pattern: Combination Constructor/Prototype Pattern)

As we have learned, one of the main principles with OOP is encapsulation—put all the inner workings of an object inside that object. To implement encapsulation in
JavaScript, we have to define the core methods and properties on that object. To do this, we will use the best pattern for encapsulation in JavaScript: the Combination
Constructor/Prototype Pattern. This name is a mouthful, but you needn’t memorize it, since we are only concerned with its implementation. Before we implement it,
let’s quickly learn a bit more about the practicality of encapsulation.

Why Encapsulation?
When you simply want to create an object just to store some data, and it is the only object of its kind, you can use an object literal and create your object. This is quite
common and you will use this simple pattern often.

However, whenever you want to create objects with similar functionalities (to use the same methods and properties), you encapsulate the main functionalities in a Function
and you use that Function’s constructor to create the objects. This is the essence of encapsulation. And it is this need for encapsulation that we are concerned with and why
we are using the Combination Constructor/Prototype Pattern.

To make practical use of OOP in JavaScript, we will build an object-oriented quiz application that uses all the principles and techniques we learn in this article. First up, our
quiz application will have users (a Users Function) who take the quiz. There will be some common properties for every user who takes the quiz: each user will have a
name, a score, an email, and the quiz scores (all the scores). These are the properties of the User object. In addition, each User object should be able to show the name and
score, save scores, and change the email. These are the methods of the object.

Because we want ALL the user objects to have these same properties and methods, we cannot use the object literal way of creating objects. We have to use a constructor
Function to encapsulate these properties and methods.

Since we know all users will have the same set of properties, it makes sense to create a Function (Class in OOP languages) that encapsulates these properties and methods.
Thus, we will use the Combination Constructor/Prototype Pattern for this.

Implementation of Combination Constructor/Prototype Pattern


The User Function:

I will explain each line.

function User (theName, theEmail) {


this.name = theName;
this.email = theEmail;
this.quizScores = [];
this.currentScore = 0;
}

User.prototype = {
constructor: User,
saveScore:function (theScoreToAdd) {
this.quizScores.push(theScoreToAdd)
},
showNameAndScores:function () {
var scores = this.quizScores.length > 0 ? this.quizScores.join(",") : "No Scores Yet";
return this.name + " Scores: " + scores;
},
changeEmail:function (newEmail) {
this.email = newEmail;
return "New Email Saved: " + this.email;
}
}

Make Instances of the User function

// A User
firstUser = new User("Richard", "[email protected]");
firstUser.changeEmail("[email protected]");
firstUser.saveScore(15);
firstUser.saveScore(10);

firstUser.showNameAndScores(); //Richard Scores: 15,10

// Another User
secondUser = new User("Peter", "[email protected]");
secondUser.saveScore(18);
secondUser.showNameAndScores(); //Peter Scores: 18

file:///Users/shafiultareq/Downloads/JavaScript%20is%20Super%20Sexy%20%7C%20JavaScript%20is%20Sexy.html Page 40 of 60
JavaScript is Super Sexy | JavaScript is Sexy 7/22/14, 3:28 PM

Explanation of Combination Constructor/Prototype Pattern


Let’s expound on each line of code so we have a thorough understanding of this pattern.

The following lines initialize the instance properties. These properties will be defined on each User instance that is created. So the values will be different for each user.
The use of the this keyword inside the function specifies that these properties will be unique to every instance of the User object:

this.name = theName;
this.email = theEmail;
this.quizScores = [];
this.currentScore = 0;

In the code below, we are overwriting the prototype property with an object literal, and we define all of our methods (that will be inherited by all the User instances) in this
object. Discussion continues after the code:

User.prototype = {
constructor: User,
saveScore:function (theScoreToAdd) {
this.quizScores.push(theScoreToAdd)
},
showNameAndScores:function () {
var scores = this.quizScores.length > 0 ? this.quizScores.join(",") : "No Scores Yet";
return this.name + " Scores: " + scores;
},
changeEmail:function (newEmail) {
this.email = newEmail;
return "New Email Saved: " + this.email;
}
}

This way of overwriting the constructor is simply for convenience, so we don’t have to write User.prototype each time, like this:

User.prototype.constructor = User;
User.prototype.saveScore = function (theScoreToAdd) {
this.quizScores.push(theScoreToAdd)
};

User.prototype.showNameAndScores = function () {
var scores = this.quizScores.length > 0 ? this.quizScores.join(",") : "No Scores Yet";
return this.name + " Scores: " + scores;
};

User.prototype.changeEmail = function (newEmail) {


this.email = newEmail;
return "New Email Saved: " + this.email;
}

By overwriting the prototype with a new object literal we have all the methods organized in one place, and you can better see the encapsulation that we are after. And of
course it is less code you have to type.

JavaScript Prototype
In JavaScript, you add methods and properties on the prototype property when you want instances of an object to inherit those methods and properties. This is the reason
we add the methods on the User.prototype property, so that they can be used by all instances of the User object. Read more about JavaScript Prototype in Plain Language.

Constructor Property
In my post JavaScript Prototype, I explained that every function has a constructor property, and this property points to the constructor of the function. For example:

function Fruit () {}
var newFruit = new Fruit ();
console.log (newFruit.constructor) // Fruit ()

The one disadvantage of overwriting the prototype is that the constructor property no longer points to the prototype, so we have to set it manually. Hence this line:

constructor: User

Prototype Methods
In the following lines, we create methods on the prototype (in the object literal) so that all instances of Users can have access to these methods.

saveScore:function (theScoreToAdd) {
this.quizScores.push(theScoreToAdd)
},
showNameAndScores:function () {
var scores = this.quizScores.length > 0 ? this.quizScores.join(",") : "No Scores Yet";
return this.name + " Scores: " + scores;
},
changeEmail:function (newEmail) {
this.email = newEmail;
return "New Email Saved: " + this.email;
}

We then created instances of the User object:

// A User
firstUser = new User("Richard", "[email protected]");
firstUser.changeEmail("[email protected]");
firstUser.saveScore(15);
firstUser.saveScore(10);

firstUser.showNameAndScores(); //Richard Scores: 15,10

// Another User
secondUser = new User("Peter", "[email protected]");
secondUser.saveScore(18);
secondUser.showNameAndScores(); //Peter Scores: 18

file:///Users/shafiultareq/Downloads/JavaScript%20is%20Super%20Sexy%20%7C%20JavaScript%20is%20Sexy.html Page 41 of 60
JavaScript is Super Sexy | JavaScript is Sexy 7/22/14, 3:28 PM

As you see, we have encapsulated all the functionality for a User inside the User Function, so that each instance of User can make use of the prototype methods (like
changeEmail) and define their own instance properties (like name and email).

With this pattern, you can use the standard operators and methods on the instances, including the instanceOf operator, the for-in loop (even hasOwnProperty), and the
constructor property.

Inheritance in JavaScript
(The Best Pattern: Parasitic Combination Inheritance)

Implementing inheritance in our quiz application will permit us to inherit functionality from parent Functions so that we can easily reuse code in our application and extend
the functionality of objects. Objects can make use of their inherited functionalities and still have their own specialized functionalities.

The best pattern for implementing inheritance in JavaScript is the Parasitic Combination inheritance [1] [2]. Before we dive into this awesome pattern, let’s see why its
practical to use inheritance in our applications.

We have successfully implemented encapsulation by enclosing all the functionality for users of our quiz application by adding all the methods and properties that each user
will need on the User function, and all instances of User will have those properties and methods.

Why Inheritance?
Next, we want to encapsulate all the functionalities for every Question. The Question function (Class in OOP languages) will have all the generic properties and methods
that every kind of question will need to have. For example, every question will have the question, the choices, and the correct answer. These will be the properties. In
addition, each question will have some methods: getCorrectAnswer and getUserAnswer, and displayQuestion.

We want our quiz application to make different types of Questions. We will implement a MultipleChoiceQuestion function and a DragDropQuestion function. To
implement these, it would not make sense to put the properties and methods outlined above (that all questions will use) inside the MultipleChoiceQuestion and
DragDropQuestion functions separately, repeating the same code. This would be redundant.

Instead, we will leave those properties and methods (that all questions will use) inside the Question object and make the MultipleChoiceQuestion and DragDropQuestion
functions inherit those methods and properties. This is where inheritance is important: we can reuse code throughout our application effectively and better maintain our
code.

Since the MultipleChoiceQuestion HTML layout and will be different from the DragDropQuestion HTML layout, the displayQuestion method will be implemented
differently in each. So we will override the displayQuestion method on the DragDropQuestion. Overriding functions is another principle of OOP.

Lets Code.

Implementation of the Parasitic Combination Inheritance Pattern


To implement this pattern, we have to use two techniques that were invented specifically for inheritance in JavaScript. Some notes about these techniques follow. No need
to memorize any of the detail, just understand and be aware of the techniques, for you will have to use them when you are ready to use OOP in your JS applications.

***** Beginning of Technical Explanation (Briefly) *****

Object.create method
Douglas Crockford created the following Object.create method [3], which is used in a fundamental way to implementing inheritance with the pattern we are using.

Here is the method Crockford created:

if (typeof Object.create !== 'function') {


Object.create = function (o) {
function F() {
}

F.prototype = o;
return new F();
};
}

This method has been added to the ECMAScript5 specification, and you can access it with Object.create (). Let’s quickly understand what it is doing:

Object.create = function (o) {


//It creates a temporary constructor F()
function F() {
}
//And set the prototype of the this constructor to the parametric (passed-in) o object
//so that the F() constructor now inherits all the properties and methods of o
F.prototype = o;

//Then it returns a new, empty object (an instance of F())


//Note that this instance of F inherits from the passed-in (parametric object) o object.
//Or you can say it copied all of the o object's properties and methods
return new F();
}

The crux of the matter with this Object.create method is that you pass into it an object that you want to inherit from, and it returns a new object that inherits from the object
you passed into it. For example:

// We have a simple cars object


var cars = {
type:"sedan",
wheels:4
};

// We want to inherit from the cars object, so we do:


var toyota = Object.create (cars); // now toyota inherits the properties from cars

file:///Users/shafiultareq/Downloads/JavaScript%20is%20Super%20Sexy%20%7C%20JavaScript%20is%20Sexy.html Page 42 of 60
JavaScript is Super Sexy | JavaScript is Sexy 7/22/14, 3:28 PM

console.log(toyota.type); // sedan

Of course we can now add more properties to the toyota object, but let’s move on.

The next function we will use for inheritance is the inheritPrototype function. This function succinctly implements the parasitic combination inheritance for us. We pass in
the parent object (or Super Class) and the child object (or Sub Class), and the function does the parasitic combination inheritance: makes the child object inherits from the
parent object.

function inheritPrototype(childObject, parentObject) {


// As discussed above, we use the Crockford’s method to copy the properties and methods from the parentObject onto the childObject
// So the copyOfParent object now has everything the parentObject has
var copyOfParent = Object.create(parentObject.prototype);

//Then we set the constructor of this new object to point to the childObject.
// Why do we manually set the copyOfParent constructor here, see the explanation immediately following this code block.
copyOfParent.constructor = childObject;

// Then we set the childObject prototype to copyOfParent, so that the childObject can in turn inherit everything from copyOfParent (from parent
childObject.prototype = copyOfParent;
}

Why did we manually set the copyOfParent.constructor?


________________________________________
We explicitly set the copyOfParent.constructor property to point to the childObject constructor because in the preceding step, var copyOfParent =
Object.create(parentObject.prototype), this is what we actually did:

// We made a new object and overwrote its prototype with the parentObject prototype:
function F() {
}
F.prototype = parentObject.prototype;
// Then it was this new F object we assigned to copyOfParent.
// All of this was done inside the Object.create () method.

So, this new F object, which we assigned to copyOfParent, doesn’t have a constructor property anymore because we overwrote its entire prototype. Whenever you
overwrite an object’s prototype (object.prototype = someVal), you also overwrite the object’s constructor property.

To make sure we have the correct value for copyOfParent constructor, we set it manually with this:
copyOfParent.constructor = childObject;

A commenter by the name of John correctly pointed our that I did not corruptly explain this bit, hence this detailed explanation.
________________________________________

Essentially, we are copying all the properties and methods from the parentObject to the childObject, but we are using the copyOfParent as an intermediary for the copy.
And because the childObject prototype was overwritten during the copy, we manually set the copyOfParent constructor to the childObject. Then we set the childObject
prototype to the copyOfParent so that the childObject inherits from the parentObject.

Okay, that was quite a bit. I am hopeful that you understand some of that
***** End of Technical Explanation (Hooray!) *****

Back to the fun stuff: Creating our quiz OOP style.


Now that we understand the inheritPrototype function we will be using, lets go ahead and implement our Question constructor.

Note that I use “constructor” and “function” interchangeably sometimes in this particular article when referring to the function, because the function will be used as a
constructor to create instances.

The Question Constructor (Parent of all Question Objects):


(Can be thought of as the Super Class for Questions)

// The Question function is the parent for all other question objects;
// All question objects will inherit from this Question constructor

function Question(theQuestion, theChoices, theCorrectAnswer) {


// Initialize the instance properties
this.question = theQuestion;
this.choices = theChoices;
this.correctAnswer = theCorrectAnswer;
this.userAnswer = "";

// private properties: these cannot be changed by instances


var newDate = new Date(),
// Constant variable: available to all instances through the instance method below. This is also a private property.
QUIZ_CREATED_DATE = newDate.toLocaleDateString();

// This is the only way to access the private QUIZ_CREATED_DATE variable


// This is an example of a privilege method: it can access private properties and it can be called publicly
this.getQuizDate = function () {
return QUIZ_CREATED_DATE;
};

// A confirmation message that the question was created


console.log("Quiz Created On: " + this.getQuizDate());

Add Prototype Methods to The Question Object


All instances of the Question object will inherit these methods, because we are adding the methods on the Question prototype.

// Define the prototype methods that will be inherited


Question.prototype.getCorrectAnswer = function () {
return this.correctAnswer;
};

file:///Users/shafiultareq/Downloads/JavaScript%20is%20Super%20Sexy%20%7C%20JavaScript%20is%20Sexy.html Page 43 of 60
JavaScript is Super Sexy | JavaScript is Sexy 7/22/14, 3:28 PM

Question.prototype.getUserAnswer = function () {
return this.userAnswer;
};

Question.prototype.displayQuestion = function () {
var questionToDisplay = "<div class='question'>" + this.question + "</div><ul>";
choiceCounter = 0;

this.choices.forEach(function (eachChoice) {
questionToDisplay += '<li><input type="radio" name="choice" value="' + choiceCounter + '">' + eachChoice + '</li>';
choiceCounter++;
});
questionToDisplay += "</ul>";

console.log (questionToDisplay);
};

Child Questions (Sub Classes of the Question object)


Now that we have the Question constructor object setup, we can inherit from it and create sub classes (children objects). The power of inheritance is that we can create all
sorts of questions now, and each can be quite versatile.

First, a Multiple Choice Question:

// Create the MultipleChoiceQuestion


function MultipleChoiceQuestion(theQuestion, theChoices, theCorrectAnswer){
// For MultipleChoiceQuestion to properly inherit from Question, here inside the MultipleChoiceQuestion constructor, we have to explicitly call the
// passing MultipleChoiceQuestion as the this object, and the parameters we want to use in the Question constructor:
Question.call(this, theQuestion, theChoices, theCorrectAnswer);
};

And then we have to use the inheritPrototype function we discussed moments ago:

// inherit the methods and properties from Question


inheritPrototype(MultipleChoiceQuestion, Question);

After we have inherited from Question, we then add methods to the MultipleChoiceQuestion function, if necessary. But we must do it after we inherit, not before, or all the
methods we define on its prototype will be overwritten. We are not adding any now.

A Drag and Drop Question


In a similar manner, we can make yet another type of question:

// Create the DragDropQuestion


function DragDropQuestion(theQuestion, theChoices, theCorrectAnswer) {
Question.call(this, theQuestion, theChoices, theCorrectAnswer);
}

// inherit the methods and properties from Question


inheritPrototype(DragDropQuestion, Question);

Overriding Methods
Overriding methods is a another principle of OOP, and we can do it easily with this pattern. Since the Drag and Drop questions will have a different HTML layout from the
Multiple Choice questions (no radio buttons, for example), we can override the displayQuestion method so it operates specifically to the Drag and Drop question needs:

// Override the displayQuestion method it inherited


DragDropQuestion.prototype.displayQuestion = function () {
// Just return the question. Drag and Drop implementation detail is beyond this article
console.log(this.question);
};

In our real Quiz application, we would create a Quiz constructor that is the main application that launches the quiz, but in this article, we can test our inheritance code by
simply doing this:

// Initialize some questions and add them to an array


var allQuestions = [
new MultipleChoiceQuestion("Who is Prime Minister of England?", ["Obama", "Blair", "Brown", "Cameron"], 3),

new MultipleChoiceQuestion("What is the Capital of Brazil?", ["São Paulo", "Rio de Janeiro", "Brasília"], 2),

new DragDropQuestion("Drag the correct City to the world map.", ["Washington, DC", "Rio de Janeiro", "Stockholm"], 0)
];

// Display all the questions


allQuestions.forEach(function (eachQuestion) {
eachQuestion.displayQuestion();
});

If you run the code, you will see that the displayQuestion for the multiple choice questions returns the question in a div tag, with choices formatted with radio buttons
inside li tags. On the other hand, the drag and drop questions displayQuestion method simply returns the question without the choices.

Nicholas Zakas stated it wonderfully, “Parasitic combination inheritance is considered the most optimal inheritance paradigm” [5] in JavaScript. If you learn it and
understand it well, you should use it in your JavaScript web applications.

You might be wondering how is the Combination Constructor/Prototype Pattern we used for Encapsulation earlier different from the Parasitic Combination Inheritance.
They are similar, but the former is best used for encapsulation (creating custom objects), and it does not have all the inheritance mechanisms such as subclassing (creating
child constructors that inherit from the parent constructor). Moreover, the inheritance pattern goes beyond setting up objects to just inherit properties and methods, it
enables child objects to themselves be parent objects of other objects, and you can use private members, overriding, and other OOP concepts.

Final Words

file:///Users/shafiultareq/Downloads/JavaScript%20is%20Super%20Sexy%20%7C%20JavaScript%20is%20Sexy.html Page 44 of 60
JavaScript is Super Sexy | JavaScript is Sexy 7/22/14, 3:28 PM

I presented you with a full walk through of implementing the best two patterns for OOP in JavaScript, and I am hopeful you understood at least the general concepts, and
that you be more inclined to use OOP in your JavaScript applications. Note that you can use OOP in even small and medium applications, not only complex applications. It
might be best to practice with the smaller applications, first, though.

I will update this article with a non-OOP version of the quiz so you can compare the two applications and judge for yourself the benefits of using OOP in JavaScript, in the
context of the examples outlined above.

Be good and do good work, and take care of yourself: sleep well, eat well, and enjoy life.

Further Reading (See links to all books in the references)


Read chapters 6 and 7 of Zakas’s Professional JavaScript for Web Developers.
Read chapters 5 and 6 of Stefanov’s JavaScript Pattens.
Read chapter 4 of Herman’s Effective JavaScript.

References
1. Professional JavaScript for Web Developers Chapter 6.
2. JavaScript Patterns Chapters 5 and 6
3. Effective JavaScript: 68 Specific Ways to Harness the Power of JavaScript Chapter 4.
4. http://javascript.crockford.com/prototypal.html
5. Professional JavaScript for Web Developers Chapter 6, page 215.

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. Topics in This Post
1. Introduction and Overview
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. 2. Design Strategies and Tools
for Responsive UI Design and
Responsive Web Design is becoming increasingly essential (we are probably a few months away from responsive being mandatory) Layout
with the ubiquity of the myriad screen sizes available today. As a result, modern web developers are expected to understand and 3. Developing Responsive, Fluid
implement responsive web designs. Layout with Percentages and
CSS3 Media Queries
What You Will Learn?
4. Core HTML5 (Semantic
HTML5 Core (HTML5 semantics, video, and audio; and later, Advanced HTML5 APIs) Elements, Audio, and Video)
Responsive Web Design (create fluid, responsive layouts from scratch and from static, pixel based layouts; responsive images,
icons, and videos; and more) 5. All the CSS3 You Need to
Tools and Strategies for Designing the user interface and static comps for responsive websites Know
HTML5 Boilerplate, Modernizr, and Initializr 6. Modern Forms with HTML5
Twitter Bootstrap 3.0 Responsive Layout and Best Practices and CSS3

7. Cross-browser HTML5 with


Resources HTML5 Boilerplate and
Modernizr
Get the following book (it is a very short read):
Responsive Web Design with HTML5 and CSS3. As with the other books I have recommended, in my humble opinion, this 8. Twitter Bootstrap 3.0
book is the best of the lot (I have done the research), so get it knowing you will get your money’s worth. Responsive Website Layout
Tutorial
Note that this book does not cover all the materials below, so you have to read the sections below in addition to the outlined
chapters in the book.

In the rest of this article, I will henceforth refer to this book as “RWD with HTML5 and CSS3.”

Downloads (including JS Libraries, module managers, and git): See the relevant sections below.

Day 1

1. Introduction and Overview


Overview of HTML5, CSS3, and Responsive Web Design
It is important to know that just about all the often-used HTML5 features and most CSS3 features are supported by all modern browsers, and developers use polyfills
to patch old browsers that lack the HTML5 and CSS3 features we need to use. As a result, HTML5 and CSS3 are in widespread use on modern websites and web
applications.

file:///Users/shafiultareq/Downloads/JavaScript%20is%20Super%20Sexy%20%7C%20JavaScript%20is%20Sexy.html Page 45 of 60
JavaScript is Super Sexy | JavaScript is Sexy 7/22/14, 3:28 PM

HTML5 is an enormous standard with an extraordinary list of features, and there are many features and standards that will not be standardized by W3C and not fully
implemented in most modern browsers for years to come. However, today there are many HTML5 features that developers are using to develop modern web
applications.

We will conceptually divide HTML5 into two parts: HTML5 Core (the semantic elements and video and audio— the HTML markup you see on the page), and
HTML5 Web Application API (features such as canvas, web sockets, server-sent events, and more—mostly the JavaScript-based aspects of the HTML5 API). In this
post, we will focus on the former, and in part 2 (a follow-up post), we will focus on the latter. We will use HTML5 to markup our web page and add video and audio.

We can use most CSS3 features today, because they are supported by all the modern browsers (IE9 is not a full modern browser, yet it still supports much of CSS3).
And for browsers that don’t support the wildly adopted CSS3 features, we will use a JavaScript library like Modernizr to detect the missing parts, and we will use
polyfills to patch the browsers accordingly, as I noted earlier. We use CSS3 for styling our website to add specialized CSS rules for detecting screens via the virtuous
CSS media queries feature.

Responsive Web Design is the notion that modern websites should adapt to, and display optimally on any, indeed all, screen sizes. This is accomplished by fluid
layouts using formulaic (a specific formula) percentages for CSS measurement instead of pixels, and using CSS media queries to target different screen sizes
(viewports).

There are generally two principal ways for developing websites to specifically target multiple devices: develop separate websites for mobile and desktop, or develop
responsive websites that adapt to all screen sizes. We will only discuss the latter, since the former is a costlier alternative that has some specific use cases depending
on the target audience and the purpose of the website. Here is a brief article on Responsive website design versus Separate websites.

Most online resources cover only the development of responsive website design, but we will also touch on, though briefly, the UI design and the static comp design,
in addition to the development.

Modernizr is a JavaScript library that detects which CSS3 and HTML5 features are not supported in browsers, and it facilitates adding targeted CSS and JavaScript
for browsers lacking core HTML5 and CSS3 feature support. It also provides (inject) semantic HTML5 elements into the page, for old browsers that natively lack
HTML5 support.

Lastly, HTML5 Boilerplate is simply a template (with HTML, CSS, and a bit of JavaScript, among a few other options like .htaccess and robots.txt) that provides
some standard, best practice functionality for developing modern websites and web applications.

We use Modernizr to add HTML5 and CSS3 support in old browsers, and HTML5 Boilerplate to provide a bevy of essential web development best practices.

Read Chapter 1 of Responsive Web Design with HTML5.

2. Design Strategies and Tools for Responsive UI Design and Layout


Before we read chapter 2 in the book and start developing a responsive website with HTML and CSS, let’s briefly touch on UI design tools and strategies for responsive
websites.

If you are not a designer, you should still read this section.

Within the last few months there have been a half dozen or more sophisticated UI tools for creating responsive UI layout, wireframes, and even complete HTML/CSS
builds. Generally, designers today can follow the conventional route and design static comps in Photoshop, or they can design interactive HTML and CSS interfaces in real
time, then export the resulting HTML and CSS code. Either of these methods works today, but over time, as responsive website designs mature, designers and clients will
find it too time consuming and costly to design dozens of static comps for numerous pages in different screen sizes using Photoshop, particularly since there is a better
alternative.

The two popular methods use today for designing the UI for responsive websites are:

Static Comps Design in Photoshop


You can create the full static design comps in Photoshop and then export the design elements and recreate the design with HTML and CSS—the process we have
used for many years. This process will eventually become obsolete because it is becoming counter productive today.

This it is still the most popular way to design websites, responsive or not. Below are some Photoshop responsive design tools to make designing responsive websites
in Photoshop more manageable:

Responsive Design Layout Patterns: Here are some examples of responsive design layout patterns that you can consider before you start designing in
Photoshop.
Rresponsinator: This shows the viewport dimensions for the major mobile devices and desktop computers. Use these dimension along with the Bootstrap grid
system to design responsive layouts.
This Photoshop Responsive Design template shows 4 designs for 4 separate screen sizes, but it does not have grids.
The Photoshop Responsive Design template at the link below uses a grid system, but the designer has rounded the percentage values for the grid system to
make the numbers more easy on the eyes and mind. As you will learn in the chapter below, the formula used to calculate fluid, percentage-based layouts results
in numbers with lengthy remainders. Here is the link to the design template.
FlatUI is a FREE UI kit of PSD templates and HTML/CSS, and it based on the flat design color scheme inspired by Windows 8 UI. I highly recommend this.
And there are two great UI frameworks that sell for a few dollars, but worth every penny:
— The Impressionist UI – User Interface Pack.
— The Bricks User Interface Framework.
Design UI in Real Time with HTML and CSS (the future of designing responsive websites)

One of the fastest growing patterns for designing responsive web sites is to use of a new genre of tools called “Interface Builders”. These tools are mostly online and
they allow you to interactively design responsive interfaces with HTML and CSS live, and you get to output the resulting HTML and CSS, and sometimes even
JavaScript, from your designs.

I use a hybrid of the aforementioned Photoshop static design along with an Interface Builder tool. For example, I would design my overall look and feel for the
desktop version of the application (I really should be doing the mobile first bit, but I am yet to transition away from my old habits), and then I use an online InterFace
Builder tool to design the full responsive layout with HTML/CSS.

Some of the best Interface builder tools are listed below. These tools are very similar and I haven’t tried all of them thoroughly enough to make a qualified
recommendation, so you have to try them and determine which is best for your needs. They are mostly easy to use.

file:///Users/shafiultareq/Downloads/JavaScript%20is%20Super%20Sexy%20%7C%20JavaScript%20is%20Sexy.html Page 46 of 60
JavaScript is Super Sexy | JavaScript is Sexy 7/22/14, 3:28 PM

Whichever tool you use, make sure you can export the HTML and CSS. Here are the new and exciting Interface Builder tools:

Adobe Edge Reflow—preview release (you cannot export HTML/CSS, though you can preview the page in the browser).
JetStrap: Build Twitter Bootstrap sites interactively.
DivShot
WebFlow

3. Developing Responsive, Fluid Layout with Percentages and CSS3 Media Queries
In Chapter 2, which you will read next, the author uses the Columnal CSS Grid system. You should follow along with the book and use the Columnal grid
system, so you can acquire the skills and learn the techniques for how to develop a responsive layout from a non-responsive HTML/CSS layout.

Bonus: I am writing a full Bootstrap 3.0 tutorial, so that you can use a real-world responsive design (mobile first) CSS/HTML framework. You will most likely
use (if you aren’t already) Twitter Bootstrap anyway, so it makes sense that you get head start with Bootstrap 3.0 in the context of this article, since are
discussing responsive web design.

Read chapter 2, “Media Queries: Supporting Differing Viewports” of RWD with HTML5 and CSS3.

You will learn more about Modernizr in section 7 below and in my Modernizr tutorial I will publish tomorrow.

Read chapter 3, “Embracing Fluid Layouts.”


More on Fluid Images and Videos
In chapter 3, you will note that the author discusses an adaptive image technique and a fluid video technique. But since the publication of the book, developers
have created some new techniques for fluid images and fluid videos. Here are a few to make note of:
Fluid Videos:
— Elastic Videos
— FitVid

Fluid Images:
— Adaptive Images (the technique discussed in the book)
— Clown Car Technique
— Fluid Images by Ethan Marcotte

In addition, I came across this very useful responsive table technique a few days ago:
Responsive Data Tables:

4. Core HTML5 (Semantic Elements, Audio, and Video)


Read chapter 4, “HTML5 for Responsive Designs.”

Day 2

5. All the CSS3 You Need to Know


Read chapters 5, 6, and 7.

6. Modern Forms with HTML5 and CSS3


Read chapter 8, “Conquer Forms with HTML5 and CSS3.”

7. Cross-browser HTML5 with HTML5 Boilerplate and Modernizr


Read chapter 9, “Solving Cross-browser Responsive Challenges.”
I will publish a post on HTML5 Boilerplate and Modernizr soon.

8. Twitter Bootstrap 3.0 Responsive Website Layout Tutorial


I have to complete the Bootstrap tutorial, which keeps growing, but I am taking a little break to complete another project and I will return to the Bootstrap tutorial
soon.

Part 2
In a follow post, we will learn Advanced HTML5 for Modern Web Application Development.
The topics will include:

Offline Applications and Local Storage


Web Workers
Canvas
History API
Server Communication (Web Sockets and Server-Sent Events)
Geolocation

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


July 5 Last Year

file:///Users/shafiultareq/Downloads/JavaScript%20is%20Super%20Sexy%20%7C%20JavaScript%20is%20Sexy.html Page 47 of 60
JavaScript is Super Sexy | JavaScript is Sexy 7/22/14, 3:28 PM

(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. Our 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. Also, we will understand how to use this correctly in every scenario, including the
ticklish situations where it usually proves elusive.

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 Topics in This Post
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. JavaScript’s this Keyword
Yes, they would. In a similar aesthetic manner, we use the this keyword as a shortcut, a referent to refer to an object. Basics

var person = { The Biggest Gotcha with


firstName :"Penelope", JavaScript “this” keyword
lastName :"Barrymore",
fullName:function () { The use of this in the global
// See how we use "this" here just like we used "he" in the example sentence? scope
console.log(this.firstName + " " + this.lastName);
When this is most
// Well, we could have also written: misunderstood and becomes
console.log(person.firstName + " " + person.lastName);
tricky
}
} Fix this when used in a method
passed as a callback
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 Fix this inside closure
attempt to access the fistName property from the person global variable, and this could lead to difficult-to-debug errors. So, we use
Fix this when method is
the “this” keyword not only for aesthetics (i.e., as a referent), but also for accuracy; its use actually makes our code more
assigned to a variable
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. Fix this when borrowing
methods
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.

this is used inside a function (let’s say function A) and it contains the value of the object that invokes function A. We need this to access methods and properties of the
object that invokes function A, especially since we don’t always know the name of the invoking object and sometimes there is no name at all to use to refer to the invoking
object. Indeed, this is really just a shortcut reference for the “antecedent object”—the invoking object.

A basic JavaScript example illustrating the use of the this keyword:

var person = {
firstName :"Penelope",
lastName :"Barrymore",
// Since the "this" keyword is used inside the showFullName method below, and the showFullName method is defined on the person object,
// "this" will have the value of the person object because the person object will invoke showFullName ()
showFullName:function () {
console.log (this.firstName + " " + this.lastName);
}

person.showFullName (); // Penelope Barrymore

A basic jQuery example with the this keyword:

// A very common piece of jQuery code

$ ("button").click (function (event) {


// $(this) will have the value of the button ($("button")) object
// because the button object invokes the click () method
console.log ($ (this).prop ("name"));
});

In the preceding jQuery example, a bit more explanation is necessary:


the use of $(this), which is jQuery’s syntax for the this keyword in JavaScript, is used inside an anonymous function, and the anonymous function is executed in the
button’s click () method. The reason $(this) is bound to the button object is because the jQuery library binds $(this) to the object that invokes the click method. Therefore,
$(this) will have the value of the jQuery button ($(“button”)) object, even though $(this) is defined inside an anonymous function that cannot itself access the “this”
variable on the outer function.

Note that the button is a DOM element on the HTML page, and it is also an object; in this case it is a jQuery object because we wrapped it in the jQuery $() function.

UPDATE: the following (“Biggest Gotcha” section) was added a couple of days after I published the article

file:///Users/shafiultareq/Downloads/JavaScript%20is%20Super%20Sexy%20%7C%20JavaScript%20is%20Sexy.html Page 48 of 60
JavaScript is Super Sexy | JavaScript is Sexy 7/22/14, 3:28 PM

The Biggest Gotcha with JavaScript “this” keyword


If you understand this one principle of JavaScript’s this, you will understand the “this” keyword with clarity: this is not assigned a value until an object invokes the function
where this is defined. Let’s call the function where this is defined the “this Function.”

Even though it appears this refers to the object where it is defined, it is not until an object invokes the this Function that this is actually assigned a value. And the value it is
assigned is based exclusively on the object that invokes the this Function. this has the value of the invoking object in most circumstances. However, there are a few
scenarios where this does not have the value of the invoking object. I touch on those scenarios later.

The use of this in the global scope


In the global scope, when the code is executing in the browser, all global variables and functions are defined on the window object. Therefore, when this is used in a global
function, it is referring to (and has the value of) the global window object (not in strict mode though, as noted earlier) that is the main container of the entire JavaScript
application or web page.

Thus:

var firstName = "Peter",


lastName = "Ally";

function showFullName () {
// "this" inside this function will have the value of the window object
// because the showFullName () function is defined in the global scope, just like the firstName and lastName
console.log (this.firstName + " " + this.lastName);
}

var person = {
firstName :"Penelope",
lastName :"Barrymore",
showFullName:function () {
// "this" on the line below refers to the person object, because the showFullName function will be invoked by person object.
console.log (this.firstName + " " + this.lastName);
}
}

showFullName (); // Peter Ally

// window is the object that all global variables and functions are defined on, hence:
window.showFullName (); // Peter Ally

// "this" inside the showFullName () method that is defined inside the person object still refers to the person object, hence:
person.showFullName (); // Penelope Barrymore

When this is most misunderstood and becomes tricky


The this keyword is most misunderstood when we borrow a method that uses this, when we assign a method that uses this to a variable, when a function that uses this is
passed as a callback function, and when this is used inside a closure—an inner function. We will look at each scenario and the solutions for maintaining the proper value of
this in each example.

A bit about “Context” before we continue


The context in JavaScript is similar to the subject of a sentence in English: “John is the winner who returned the money.” The subject of the sentence is John, and we can
say the context of the sentence is John because the focus of the sentence is on him at this particular time in the sentence. Even the “who” pronoun is referring to John, the
antecedent. And just like we can use a semicolon to switch the subject of the sentence, we can have an object that is current context and switch the context to another object
by invoking the function with another object.

Similarly, in JavaScript code:

var person = {
firstName :"Penelope",
lastName :"Barrymore",
showFullName:function () {
// The "context"
console.log (this.firstName + " " + this.lastName);
}
}

// The "context", when invoking showFullName, is the person object, when we invoke the showFullName () method on the person object.
// And the use of "this" inside the showFullName() method has the value of the person object,
person.showFullName (); // Penelope Barrymore

// If we invoke showFullName with a different object:


var anotherPerson = {
firstName :"Rohit",
lastName :"Khan"
};

// We can use the apply method to set the "this" value explicitly—more on the apply () method later.
// "this" gets the value of whichever object invokes the"this Function", hence:
person.showFullName.apply (anotherPerson); // Rohit Khan

// So the context is now anotherPerson because anotherPerson invoked the person.showFullName () method by virtue of using the apply () method

The takeaway is that the object that invokes the this Function is in context, and we can change the context by invoking the this Function with another object; then this new
object is in context.

Here are scenarios when the this keyword becomes tricky. The examples include solutions to fix errors with this:

file:///Users/shafiultareq/Downloads/JavaScript%20is%20Super%20Sexy%20%7C%20JavaScript%20is%20Sexy.html Page 49 of 60
JavaScript is Super Sexy | JavaScript is Sexy 7/22/14, 3:28 PM

1. Fix this when used in a method passed as a callback


Things get a touch hairy when we pass a method (that uses this) as a parameter to be used as a callback function. For example:

// We have a simple object with a clickHandler method that we want to use when a button on the page is clicked
var user = {
data:[
{name:"T. Woods", age:37},
{name:"P. Mickelson", age:43}
],
clickHandler:function (event) {
var randomNum = ((Math.random () * 2 | 0) + 1) - 1; // random number between 0 and 1

// This line is printing a random person's name and age from the data array
console.log (this.data[randomNum].name + " " + this.data[randomNum].age);
}
}

// The button is wrapped inside a jQuery $ wrapper, so it is now a jQuery object


// And the output will be undefined because there is no data property on the button object
$ ("button").click (user.clickHandler); // Cannot read property '0' of undefined

In the code above, since the button ($(“button”)) is an object on its own, and we are passing the user.clickHandler method to its click() method as a callback, we
know that this inside our user.clickHandler method will no longer refer to the user object. this will now refer to the object where the user.clickHandler method is
executed because this is defined inside the user.clickHandler method. And the object that is invoking user.clickHandler is the button object—user.clickHandler will
be executed inside the button object’s click method.

Note that even though we are calling the clickHandler () method with user.clickHandler (which we have to do, since clickHandler is a method defined on user), the
clickHandler () method itself will be executed with the button object as the context to which “this” now refers. So this now refers to is the button ($(“button”)) object.

At this point, it should be apparent that when the context changes—when we execute a method on some other object than where the object was originally defined, the
this keyword no longer refers to the original object where ‘this” was originally defined, but it now refers to the object that invokes the method where this was
defined.

Solution to fix this when a method is passed as a callback function:


Since we really want this.data to refer to the data property on the user object, we can use the Bind (), Apply (), or Call () method to specifically set the value of this.

I have written an exhaustive article, JavaScript’s Apply, Call, and Bind Methods are Essential for JavaScript Professionals, on these methods, including how to use
them to set the this value in various misunderstood scenarios. Rather than re-post all the details here, I recommend you read that entire article, which I consider a
must read for JavaScript Professionals.

To fix this problem in the preceding example, we can use the bind method thus:

Instead of this line:

$ ("button").click (user.clickHandler);

We have to bind the clickHandler method to the user object like this:

$("button").click (user.clickHandler.bind (user)); // P. Mickelson 43

— View a working example of this on JSBin

2. Fix this inside closure


Another instance when this is misunderstood is when we use an inner method (a closure). It is important to take note that closures cannot access the outer function’s
this variable by using the this keyword because the this variable is accessible only by the function itself, not by inner functions. For example:

var user = {
tournament:"The Masters",
data :[
{name:"T. Woods", age:37},
{name:"P. Mickelson", age:43}
],

clickHandler:function () {
// the use of this.data here is fine, because "this" refers to the user object, and data is a property on the user object.

this.data.forEach (function (person) {


// But here inside the anonymous function (that we pass to the forEach method), "this" no longer refers to the user object.
// This inner function cannot access the outer function's "this"

console.log ("What is This referring to? " + this); //[object Window]

console.log (person.name + " is playing at " + this.tournament);


// T. Woods is playing at undefined
// P. Mickelson is playing at undefined
})
}

user.clickHandler(); // What is This referring to? [object Window]

this inside the anonymous function cannot access the outer function’s this, so it is bound to the global window object, when strict mode is not being used.

Solution to maintain this inside anonymous functions:


To fix the problem with using this inside the anonymous function passed to the forEach method, we use a common practice in JavaScript and set the this value to
another variable before we enter the forEach

file:///Users/shafiultareq/Downloads/JavaScript%20is%20Super%20Sexy%20%7C%20JavaScript%20is%20Sexy.html Page 50 of 60
JavaScript is Super Sexy | JavaScript is Sexy 7/22/14, 3:28 PM

method:

var user = {
tournament:"The Masters",
data :[
{name:"T. Woods", age:37},
{name:"P. Mickelson", age:43}
],

clickHandler:function (event) {
// To capture the value of "this" when it refers to the user object, we have to set it to another variable here:
// We set the value of "this" to theUserObj variable, so we can use it later
var theUserObj = this;
this.data.forEach (function (person) {
// Instead of using this.tournament, we now use theUserObj.tournament
console.log (person.name + " is playing at " + theUserObj.tournament);
})
}

user.clickHandler();
// T. Woods is playing at The Masters
// P. Mickelson is playing at The Masters

It is worth noting that many JavaScript developers like to name a variable “that,” as seen below, to set the value of this. The use of the word “that” is very awkward
for me, so I try to name the variable a noun that describes which object “this” is referring to, hence my use of var theUserObj = this in the preceding code.

// A common practice amongst JavaScript users is to use this code


var that = this;

— View a working example of this on JSBin

3. Fix this when method is assigned to a variable


The this value escapes our imagination and is bound to another object, if we assign a method that uses this to a variable. Let’s see how:

// This data variable is a global variable


var data = [
{name:"Samantha", age:12},
{name:"Alexis", age:14}
];

var user = {
// this data variable is a property on the user object
data :[
{name:"T. Woods", age:37},
{name:"P. Mickelson", age:43}
],
showData:function (event) {
var randomNum = ((Math.random () * 2 | 0) + 1) - 1; // random number between 0 and 1

// This line is adding a random person from the data array to the text field
console.log (this.data[randomNum].name + " " + this.data[randomNum].age);
}

// Assign the user.showData to a variable


var showUserData = user.showData;

// When we execute the showUserData function, the values printed to the console are from the global data array, not from the data array in
//
showUserData (); // Samantha 12 (from the global data array)

Solution for maintaining this when method is assigned to a variable:


We can fix this problem by specifically setting the this value with the bind method:

// Bind the showData method to the user object


var showUserData = user.showData.bind (user);

// Now we get the value from the user object, because the this keyword is bound to the user object
showUserData (); // P. Mickelson 43

4. Fix this when borrowing methods


Borrowing methods is a common practice in JavaScript development, and as JavaScript developers, we will certainly encounter this practice time and again. And
from time to time, we will engage in this time-saving practice as well. For more on borrowing methods, read my in-depth article, JavaScript’s Apply, Call, and Bind
Methods are Essential for JavaScript Professionals.

Let’s examine the relevance of this in the context of borrowing methods:

// We have two objects. One of them has a method called avg () that the other doesn't have
// So we will borrow the (avg()) method
var gameController = {
scores :[20, 34, 55, 46, 77],
avgScore:null,
players :[
{name:"Tommy", playerID:987, age:23},
{name:"Pau", playerID:87, age:33}
]
}

file:///Users/shafiultareq/Downloads/JavaScript%20is%20Super%20Sexy%20%7C%20JavaScript%20is%20Sexy.html Page 51 of 60
JavaScript is Super Sexy | JavaScript is Sexy 7/22/14, 3:28 PM

var appController = {
scores :[900, 845, 809, 950],
avgScore:null,
avg :function () {

var sumOfScores = this.scores.reduce (function (prev, cur, index, array) {


return prev + cur;
});

this.avgScore = sumOfScores / this.scores.length;


}
}

//If we run the code below,


// the gameController.avgScore property will be set to the average score from the appController object "scores" array

// Don't run this code, this is just for illustration; we want the appController.avgScore to remain null
gameController.avgScore = appController.avg();

The avg method’s “this” keyword will not refer to the gameController object, it will refer to the appController object because it is being invoked on the
appController.

Solution for fixing this when borrowing methods:


To fix the issue and make sure that this inside the appController.avg () method refers to gameController, we can use the apply () method thus:

// Note that we are using the apply () method, so the 2nd argument has to be an array—the arguments to pass to the appController.avg () me
appController.avg.apply (gameController, gameController.scores);

// The avgScore property was successfully set on the gameController object, even though we borrowed the avg () method from the appControll
console.log (gameController.avgScore); // 46.4

// appController.avgScore is still null; it was not updated, only gameController.avgScore was updated
console.log (appController.avgScore); // null

The gameController object borrows the appController’s avg () method. The “this” value inside the appController.avg () method will be set to the gameController
object because we pass the gameController object as the first parameter to the apply () method. The first parameter in the apply method always sets the value of “this”
explicitly.

— View a working example of this on JSBin

Final Words
I am hopeful you have gained a better understanding of this in JavaScript, if you weren’t already very familiar with it. Now you have the tools (bind, apply, call, and setting
this to a variable) necessary to conquer the use of JavaScript’s this keyword in every scenario.

As you have read, this gets a bit hairy in situations where the context of where this was defined changes, especially in callback functions, when invoked with a different
object, and when borrowing methods. Always remember that this is assigned the value of the object that invoked the this Function.

Be good and keep coding.

16 JavaScript Concepts JavaScript Professionals Must Know Well


July 9 Last Year

(Essential JavaScript Concepts for Modern JavaScript Development )

If you plan to work as JavaScript Professional, there are some JavaScript concepts and JavaScript-related web-development technologies that you must know well,
particularly as a modern JavaScript developer. If you know the 16 concepts enumerated 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 JavaScript-only web application. While the 16 concepts enumerated
below are neither complex nor difficult, you will get the most benefit from them if you already know at least some basic JavaScript.

These are the sixteen concepts that every modern JavaScript developer must know 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. JavaScript Custom Events with PubSub (Published in 3 weeks—around August 2)


12. Unit Testing Your JavaScript Applications is Essential (Published in 5 weeks—around August 14)
13. DOM (Document Object Model) and BOM (Browser Object Model)
14. ECMAScript 3 and 5
15. The Best JavaScript Front-end Frameworks You Should be Using

file:///Users/shafiultareq/Downloads/JavaScript%20is%20Super%20Sexy%20%7C%20JavaScript%20is%20Sexy.html Page 52 of 60
JavaScript is Super Sexy | JavaScript is Sexy 7/22/14, 3:28 PM

16. Preventing and Handling JavaScript Errors and Debugging Your Code

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 know well by now, 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 they are used frequently in JavaScript for borrowing methods and explicitly for setting the this value. We also use Apply for
variable-arity functions.

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 these three methods are used in JavaScript. While Apply and Call are part of ECMAScript 3 Topics in This Post
(available on IE 6, 7, 8, and modern browsers), ECMAScript 5 (available only on modern browsers) added the Bind method. These 3 JavaScript’s Bind Method
Function methods are workhorses and sometimes you absolutely need one of them. Let’s begin with the Bind method.
JavaScript’s Bind Allows Us to
Set the this Value on Methods
JavaScript’s Bind Method Bind () Allows us to Borrow
Methods
The bind () method is used primarily to call a function with the this value set explicitly. It other words, bind () allows you to easily set
which specific object will be bound to this when a function or method is invoked. JavaScript's Bind Allows Us to
Curry a Function
This might seem relatively trivial, but oftentimes the this value in methods and functions must be set explicitly when you need a
specific object bound to the function’s this value. JavaScript's Apply and Call
Methods
The problem is that when we use the this keyword in methods, and we call said methods from a receiver object, Set the this value with Apply or
sometimes this is not bound to the object that we intended. And this results in errors in our code. Call

Before we look at the code for this section, it is imperative that we understand the this keyword in JavaScript. If you don’t already Borrowing Functions with Apply
understand the “this” keyword in JavaScript, read my article, Understand JavaScript’s “this” With Clarity, and Master It, for if you and Call (A Must Know)
don’t understand this thoroughly, you will have trouble understanding some of the concepts discussed below. In fact, most of the
Use Apply () to Execute
concepts regarding setting the “this” value that I discuss in this article I also discussed in the “Understand JavaScript’s this” article
Variable-Arity Functions
because the discussion of setting “this” is exemplified with Bind, Apply, and Call.

JavaScript’s Bind Allows Us to Set the this Value on Methods


When this button below is clicked, the text field is populated with a random name.

// <button>Get Random Person</button>


// <input type="text">

var user = {
data :[
{name:"T. Woods", age:37},
{name:"P. Mickelson", age:43}
],
clickHandler:function (event) {
var randomNum = ((Math.random () * 2 | 0) + 1) - 1; // random number between 0 and 1

// This line is adding a random person from the data array to the text field
$ ("input").val (this.data[randomNum].name + " " + this.data[randomNum].age);
}

// Assign an eventHandler to the button's click event


$ ("button").click (user.clickHandler);

When you click on the button, you get an error because this in the clickHandler () method is bound to the button HTML element, since that is the object that the
clickHandler method is executed on.

This particular problem is quite common in JavaScript, and JavaScript frameworks like Backbone.js and libraries like jQuery automatically do the bindings for us, so
that this is always bound to the object we intended.

To fix this problem in the preceding example, we can use the bind method thus:
Instead of this line:

$ ("button").click (user.clickHandler);

We simply have to bind the clickHandler method to the user object like this:

$ ("button").click (user.clickHandler.bind (user));

file:///Users/shafiultareq/Downloads/JavaScript%20is%20Super%20Sexy%20%7C%20JavaScript%20is%20Sexy.html Page 53 of 60
JavaScript is Super Sexy | JavaScript is Sexy 7/22/14, 3:28 PM

Note that another way to fix the this value is that you can pass an anonymous callback function to the click () method and jQuery will bound this inside the
anonymous function to the button object.

Because the bind method was introduced in ECMAScript 5, it is unavailable in IE < 9 and Firefox 3.x.
Here is an implementation that you can include in your code if you are targeting older browsers:

// Credit to Douglas Crockford for this bind method


if (!Function.prototype.bind) {
Function.prototype.bind = function (oThis) {
if (typeof this !== "function") {
// closest thing possible to the ECMAScript 5 internal IsCallable function
throw new TypeError ("Function.prototype.bind - what is trying to be bound is not callable");
}

var aArgs = Array.prototype.slice.call (arguments, 1),


fToBind = this,
fNOP = function () {
},
fBound = function () {
return fToBind.apply (this instanceof fNOP && oThis
? this
: oThis,
aArgs.concat (Array.prototype.slice.call (arguments)));
};

fNOP.prototype = this.prototype;
fBound.prototype = new fNOP ();

return fBound;
};
}

Let's continue with the same example we have used above. The this value is also bound to another object if we assign the method (where this is defined) to a variable.
This demonstrates:

// This data variable is a global variable


var data = [
{name:"Samantha", age:12},
{name:"Alexis", age:14}
]

var user = {
// local data variable
data :[
{name:"T. Woods", age:37},
{name:"P. Mickelson", age:43}
],
showData:function (event) {
var randomNum = ((Math.random () * 2 | 0) + 1) - 1; // random number between 0 and 1

console.log (this.data[randomNum].name + " " + this.data[randomNum].age);


}

// Assign the showData method of the user object to a variable


var showDataVar = user.showData;

showDataVar (); // Samantha 12 (from the global data array, not from the local data array)

When we execute the showDataVar () function, the values printed to the console are from the global data array, not the data array in the user object. This happens
because showDataVar () is executed as a global function and use of this inside showDataVar () is bound to the global scope, which is the window object in browsers.

Again, we can fix this problem by specifically setting the "this" value with the bind method:

// Bind the showData method to the user object


var showDataVar = user.showData.bind (user);

// Now the we get the value from the user object because the this keyword is bound to the user object
showDataVar (); // P. Mickelson 43

Bind () Allows us to Borrow Methods


In JavaScript, we can pass functions around, return them, borrow them, and the like. And the bind () method makes it super easy to borrow methods.

Here is an example using bind () to borrow a method:

// Here we have a cars object that does not have a method to print its data to the console
var cars = {
data:[
{name:"Honda Accord", age:14},
{name:"Tesla Model S", age:2}
]

// We can borrow the showData () method from the user object we defined in the last example.
// We bind the user.showData method to the cars object we just created.
cars.showData = user.showData.bind (cars);

file:///Users/shafiultareq/Downloads/JavaScript%20is%20Super%20Sexy%20%7C%20JavaScript%20is%20Sexy.html Page 54 of 60
JavaScript is Super Sexy | JavaScript is Sexy 7/22/14, 3:28 PM

cars.showData (); // Honda Accord 14

One problem with this example is that we are adding a new method (showData) on the cars object and we might not want to do that just to borrow a method because
the cars object might already have a property or method name showData, and we don't want to overwrite it accidentally. As we will see with Apply and Call
(discussed next), it is best to borrow methods with either the Apply or Call methods.

JavaScript's Bind Allows Us to Curry a Function


Function Currying, also known as partial function application, is the use of a function (that accept one or more arguments) that returns a new function with some of
the arguments already set. The function that is returned has access to the stored arguments and variables of the outer function. This sounds way more complex than it
actually is, so let's code.

Let's use the bind () method for currying. First we have a simple greet () function that accepts 3 parameters:

function greet (gender, age, name) {


// if a male, use Mr., else use Ms.
var salutation = gender === "male" ? "Mr. " : "Ms. ";

if (age > 25) {


return "Hello, " + salutation + name + ".";
}
else {
return "Hey, " + name + ".";
}
}

And we use the bind () method to curry (preset one or more of the parameters) our greet () function. The first argument of the bind () method sets the this value, as
we discussed earlier:

// So we are passing null because we are not using the "this" keyword in our greet function.
var greetAnAdultMale = greet.bind (null, "male", 45);

greetAnAdultMale ("John Hartlove"); // "Hello, Mr. John Hartlove."

var greetAYoungster = greet.bind (null, "", 16);


greetAYoungster ("Alex"); // "Hey, Alex."
greetAYoungster ("Emma Waterloo"); // "Hey, Emma Waterloo."

When we use the bind () method for currying, all the parameters of the greet () function, except the last (rightmost) argument, are preset. So it is the rightmost
argument that we are changing when we call the new functions that were curried from the greet () function. Again, I discuss currying at length in a separate blog post,
and you will see how we can easily create very powerful functions with Currying and Compose, two Functional JavaScript concepts.

So, with the bind () method, we can explicitly set the this value for invoking methods on objects, we can borrow
and copy methods, and assign methods to variable to be executed as functions. And as outlined in the Currying Tip
earlier,
you can use bind for currying.

JavaScript's Apply and Call Methods


The Apply and Call methods are two of the most often used Function methods in
JavaScript, and for good reason: they allow us to borrow functions and set the this value in function invocation. And the apply function in particular allows us to execute a
function with an array of parameters, such that each parameter is passed to the function individually when the function executes—great for variadic functions.

Set the this value with Apply or Call


Just as in the bind () example, we can also set the this value when invoking functions by using the Apply or Call methods. The first parameter in the call and apply
methods set the this value to the object that the function is invoked upon.

Here is a very quick, illustrative example for starters before we get into more complex usages of Apply and Call:

// global variable for demonstration


var avgScore = "global avgScore";

//global function
function avg (arrayOfScores) {
// Add all the scores and return the total
var sumOfScores = arrayOfScores.reduce (function (prev, cur, index, array) {
return prev + cur;
});

// The "this" keyword here will be bound to the global object, unless we set the "this" with Call or Apply
this.avgScore = sumOfScores / arrayOfScores.length;
}

var gameController = {
scores :[20, 34, 55, 46, 77],
avgScore:null
}

// If we execute the avg function thus, "this" inside the function is bound to the global window object:
avg (gameController.scores);
// Proof that the avgScore was set on the global window object
console.log (window.avgScore); // 46.4
console.log (gameController.avgScore); // null

file:///Users/shafiultareq/Downloads/JavaScript%20is%20Super%20Sexy%20%7C%20JavaScript%20is%20Sexy.html Page 55 of 60
JavaScript is Super Sexy | JavaScript is Sexy 7/22/14, 3:28 PM

// reset the global avgScore


avgScore = "global avgScore";

// To set the "this" value explicitly, so that "this" is bound to the gameController,
// We use the call () method:
avg.call (gameController, gameController.scores);

console.log (window.avgScore); //global avgScore


console.log (gameController.avgScore); // 46.4

Note that the first argument to call () sets the this value. In the preceding example, it is set to
the gameController object. The other arguments after the first argument are passed as parameters to the
avg () function.

The apply and call methods are almost identical when setting the this value except that you pass the function parameters to apply () as an array, while you have to list
the parameters individually to pass them to the call () method. More on this follows. Meanwhile, the apply () method also has another feature that the call () method
doesn't have, as we will soon see.

Use Call or Apply To Set this in Callback Functions


I borrowed this little section from my article, Understand JavaScript Callback Functions and Use Them.

// Define an object with some properties and a method


// We will later pass the method as a callback function to another function
var clientData = {
id: 094545,
fullName: "Not Set",
// setUserName is a method on the clientData object
setUserName: function (firstName, lastName) {
// this refers to the fullName property in this object
this.fullName = firstName + " " + lastName;
}
}

function getUserInput (firstName, lastName, callback, callbackObj) {


// The use of the Apply method below will set the "this" value to callbackObj
callback.apply (callbackObj, [firstName, lastName]);
}

The Apply method sets the this value to callbackObj. This allows us to execute the callback function with the this value set explicitly, so the parameters passed to the
callback function will be set on the clientData object:

// The clientData object will be used by the Apply method to set the "this" value
getUserInput ("Barack", "Obama", clientData.setUserName, clientData);
// the fullName property on the clientData was correctly set
console.log (clientData.fullName); // Barack Obama

The Apply, Call, and Bind methods are all used to set the this value when invoking a method, and they do it in slightly different ways to allow use direct control and
versatility in our JavaScript code. The this value in JavaScript is as important as any other part of the language, and we have the 3 aforementioned methods are the
essential tools to setting and using this effectively and properly.

Borrowing Functions with Apply and Call (A Must Know)


The most common use of the Apply and Call methods in JavaScript is probably to borrow functions. We can borrow functions with the Apply and Call methods as
we did with the bind method, but in a more robust and versatile manner.

Here are some examples:

Borrowing Array Methods


Arrays come with a number of useful methods for iterating and modifying arrays, but unfortunately, Objects do not have as many native methods. Nonetheless,
since objects can be expressed in a manner similar to an Array (known as an array-like object), and most important, because all of the Array methods are
generic (except toString and toLocaleString), we can borrow Array methods and use them on objects that are array-like.

An array-like object is an object that has its keys defined as non-negative integers. It is best to specifically add a length property on the object that has the
length of the object, since the a length property does not exist on objects it does on Arrays.

It is important for me to note (for clarity, especially for new JavaScript developers) that in the following examples, when we call Array.prototype, we are
reaching into the Array object and on its prototype (where all its methods are defined for inheritance). And it is from there—the source—that we are borrowing
the Array methods. Hence the use of code like Array.prototype.slice—the slice method that is defined on the Array prototype.

Let's create an array-like object and borrow some array methods to operate on the our array-like object. Keep in mind the array-like object is a real object, it is
not an array at all:

// An array-like object: note the non-negative integers used as keys


var anArrayLikeObj = {0:"Martin", 1:78, 2:67, 3:["Letta", "Marieta", "Pauline"], length:4 };

Now, if wish to use any of the common Array methods on our object, we can:

// Make a quick copy and save the results in a real array:


// First parameter sets the "this" value
var newArray = Array.prototype.slice.call (anArrayLikeObj, 0);

console.log (newArray); // ["Martin", 78, 67, Array[3]]

file:///Users/shafiultareq/Downloads/JavaScript%20is%20Super%20Sexy%20%7C%20JavaScript%20is%20Sexy.html Page 56 of 60
JavaScript is Super Sexy | JavaScript is Sexy 7/22/14, 3:28 PM

// Search for "Martin" in the array-like object


console.log (Array.prototype.indexOf.call (anArrayLikeObj, "Martin") === -1 ? false : true); // true

// Try using an Array method without the call () or apply ()


console.log (anArrayLikeObj.indexOf ("Martin") === -1 ? false : true); // Error: Object has no method 'indexOf'

// Reverse the object:


console.log (Array.prototype.reverse.call (anArrayLikeObj));
// {0: Array[3], 1: 67, 2: 78, 3: "Martin", length: 4}

// Sweet. We can pop too:


console.log (Array.prototype.pop.call (anArrayLikeObj));
console.log (anArrayLikeObj); // {0: Array[3], 1: 67, 2: 78, length: 3}

// What about push?


console.log (Array.prototype.push.call (anArrayLikeObj, "Jackie"));
console.log (anArrayLikeObj); // {0: Array[3], 1: 67, 2: 78, 3: "Jackie", length: 4}

We get all the great benefits of an object and we are still able to use Array methods on our object, when we setup our object as an array-like object and borrow
the Array methods. All of this is made possible by the virtue of the call or apply method.

The arguments object that is a property of all JavaScript functions is an array-like object, and for this reason, one of the most popular uses of the call () and
apply () methods is to extract the parameters passed into a function from the arguments object.

Here is an example I took from the Ember.js source, with comments I added:

function transitionTo (name) {


// Because the arguments object is an array-like object
// We can use the slice () Array method on it
// The number "1" parameter means: return a copy of the array from index 1 to the end. Or simply: skip the first item

var args = Array.prototype.slice.call (arguments, 1);

// I added this bit so we can see the args value


console.log (args);

// I commented out this last line because it is beyond this example


//doTransition(this, name, this.updateURL, args);
}

// Because the slice method copied from index 1 to the end, the first item "contact" was not returned
transitionTo ("contact", "Today", "20"); // ["Today", "20"]

The args variable is a real array. It has a copy of all the parameters passed to the transitionTo function.

From this example, we learn that a quick way to get all the arguments (as an array) passed to a function is to do:

// We do not define the function with any parameters, yet we can get all the arguments passed to it
function doSomething () {
var args = Array.prototype.slice.call (arguments);
console.log (args);
}

doSomething ("Water", "Salt", "Glue"); // ["Water", "Salt", "Glue"]

We will discuss how to use the apply method with the arguments array-like object again for variadic functions. More on this later.

Borrowing String Methods with Apply and Call


Like the preceding example, we can also use apply () and call () to borrow String methods. Since Strings are immutable, only the non-manipulative arrays
work on them, so you cannot use reverse, pop and the like.

Borrow Other Methods and Functions


Since we are borrowing, lets go all in and borrow from our own custom methods and functions, not just from Array and String:

var gameController = {
scores :[20, 34, 55, 46, 77],
avgScore:null,
players :[
{name:"Tomy", playerID:987, age:23},
{name:"Pau", playerID:87, age:33}
]
}

var appController = {
scores :[900, 845, 809, 950],
avgScore:null,
avg :function () {

var sumOfScores = this.scores.reduce (function (prev, cur, index, array) {


return prev + cur;
});

this.avgScore = sumOfScores / this.scores.length;


}
}

// Note that we are using the apply () method, so the 2nd argument has to be an array
appController.avg.apply (gameController, gameController.scores);
console.log (gameController.avgScore); // 46.4

// appController.avgScore is still null; it was not updated, only gameController.avgScore was updated

file:///Users/shafiultareq/Downloads/JavaScript%20is%20Super%20Sexy%20%7C%20JavaScript%20is%20Sexy.html Page 57 of 60
JavaScript is Super Sexy | JavaScript is Sexy 7/22/14, 3:28 PM

console.log (appController.avgScore); // null

Sure, it is just as easy and, even recommended, to borrow our own custom methods and functions. The gameController object borrows the appController
object's avg () method. The "this" value defined in the avg () method will be set to the first parameter—the gameController object.

You might be wondering what will happen if the original definition of the method we are borrowing changes. Will the borrowed (copied) method change as well, or
is the copied method a full copy that does not refer back to the original method? Let's answer these questions with a quick, illustrative example:

appController.maxNum = function () {
this.avgScore = Math.max.apply (null, this.scores);
}

appController.maxNum.apply (gameController, gameController.scores);


console.log (gameController.avgScore); // 77

As expected, if we change the original method, the changes are reflected in the borrowed instances of that method. This is expected for good reason: we never made a
full copy of the method, we simply borrowed it (referred directly to its current implementation).

Use Apply () to Execute Variable-Arity Functions


To wrap up our discussion on the versatility and usefulness of the Apply, Call, and Bind methods, we will discuss a neat
little feature of the Apply method: execute functions with an array of arguments.

We can pass an array with of arguments to a function and, by virtue of using the apply () method, the function will execute the
items in the array as if we called the function like this:

createAccount (arrayOfItems[0], arrayOfItems[1], arrayOfItems[2], arrayOfItems[3]);

This technique is especially used for creating variable-arity, also known as variadic functions.
These are functions that accept any number of arguments instead of a fixed number of arguments. The arity of a function specifies the number of arguments the
function was defined to accept.

The Math.max() method is an example of a common variable-arity function in JavaScript:

// We can pass any number of arguments to the Math.max () method


console.log (Math.max (23, 11, 34, 56)); // 56

But what if we have an array of numbers to pass to Math.max? We cannot do this:

var allNumbers = [23, 11, 34, 56];


// We cannot pass an array of numbers to the the Math.max method like this
console.log (Math.max (allNumbers)); // NaN

This is where the apply () method helps us execute variadic functions. Instead of the above, we have to pass the array of numbers using apply () thus:

var allNumbers = [23, 11, 34, 56];


// Using the apply () method, we can pass the array of numbers:
console.log (Math.max.apply (null, allNumbers)); // 56

As we have learned earlier, the fist argument to apply () sets the "this" value, but "this" is not used in the Math.max () method, so we pass null.

Here is an example of our own variadic function to further illustrate the concept of using the apply () method in
this capacity:

var students = ["Peter Alexander", "Michael Woodruff", "Judy Archer", "Malcolm Khan"];

// No specific parameters defined, because ANY number of parameters are accepted


function welcomeStudents () {
var args = Array.prototype.slice.call (arguments);

var lastItem = args.pop ();


console.log ("Welcome " + args.join (", ") + ", and " + lastItem + ".");
}

welcomeStudents.apply (null, students);


// Welcome Peter Alexander, Michael Woodruff, Judy Archer, and Malcolm Khan.

Final Words
The Call, Apply, and Bind methods are indeed workhorses and should be part of your JavaScript repertoire for
setting the this value in functions, creating and executing variadic functions, and borrowing methods and functions. As a JavaScript developer, you would likely encounter
and use these functions time and again. So be sure you understand them well.

Be good, imagine, and create.

Beautiful JavaScript: Easily Create Chainable (Cascading) Methods for


Expressiveness
August 13 Last Year

(Part of the “12 Powerful JavaScript Tips” Series)

Prerequisites:

file:///Users/shafiultareq/Downloads/JavaScript%20is%20Super%20Sexy%20%7C%20JavaScript%20is%20Sexy.html Page 58 of 60
JavaScript is Super Sexy | JavaScript is Sexy 7/22/14, 3:28 PM

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

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", lastName:"MalCom", email:"[email protected]", id:102},
{firstName:"Peter", lastName:"breCht", email:"[email protected]", id:103},
{firstName:"RoHan", lastName:"sahu", email:"[email protected]", 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):

userController.findUser("[email protected]").formatName()
.createLayout().displayUser();

Here is the result on JSBin:


http://jsbin.com/erewat/1/edit

Why Use Cascading in JavaScript?


There is no need to create temporary variables to save each step of the process. For example, without chaining, our code will look like this:

var aUser = userController.findUser("[email protected]");

file:///Users/shafiultareq/Downloads/JavaScript%20is%20Super%20Sexy%20%7C%20JavaScript%20is%20Sexy.html Page 59 of 60
JavaScript is Super Sexy | JavaScript is Sexy 7/22/14, 3:28 PM

var formatUserName = aUser.formatName();


var layoutHTML = formatUserName.createLayout();
userController.displayUser(layoutHTML);

Now, every line of code clearly and succinctly expresses what it is doing, particularly when the name of each method is defined using verbs.
Our code is more maintainable because we have simple, lean, specialized methods.
Overall, one can easily read the “chainable” code, effortlessly type it, and comfortably understand it.

How Does Chaining Methods Work in JavaScript?


When each method returns this, the entire object that called the method is returned. The execution proceeds thus:

// Use the userController object to execute the findUser method


userController.findUser("[email protected]")

Because we are executing the findUser method on the userController object, and because the findUser method returns “this” (the object that invoked it), the entire
userController object is returned and passed to the next method in the chain, since the “this” keyword in findUser holds the value of the object that invoked it.

Therefore, this occurs next:

userController.formatName();

Similarly, the formatName method returns the userController object, so expectedly, this follows:

userController.createLayout();

Followed by:

<script>
userController.displayUser();

Each step of the way, we are returning the userController object and invoking methods on it.

Closing Words
This was probably the shortest post I have written so far. But I am hopeful it is just as informative as the others and you will start using cascading to make your JavaScript
code more expressive, and indeed more beautiful.

As always, if you see any bugs or grammar typos or mistakes, please notify me promptly.

Thanks for your time.

file:///Users/shafiultareq/Downloads/JavaScript%20is%20Super%20Sexy%20%7C%20JavaScript%20is%20Sexy.html Page 60 of 60

You might also like