JavaScript is Super Sexy _ JavaScript is Sexy
JavaScript is Super Sexy _ JavaScript is Sexy
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.
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.
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.
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?
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?
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.
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.
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
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.
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.
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.
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):
// 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 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”}
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
function Plant () {
this.country = "Mexico";
this.isOrganic = true;
}
// Set the Fruit's prototype to Plant's constructor, thus inheriting all of Plant.prototype methods and properties.
Fruit.prototype = new Plant ();
// 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).
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.
// 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 ();
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
// 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.
Additional Information
For more on JavaScript Objects, read Chapter 6 of JavaScript: The Definitive Guide (6th Edition, May 2011) by David Flanagan.
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.
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:
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.
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:
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.
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 = {};
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.
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.
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:
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
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”;
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).
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
Accessing a property on an object that does not exist will result in undefined.
To find out if a property exists on an object (either as an inherited or an own property), you use the in operator:
// 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.
// 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
// 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
// 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";
}
//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.
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
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).
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
// 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.
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:
// 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"}';
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.
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.
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
// 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 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);
}
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);
}
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
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";
}
// The second declaration of firstName simply re-declares and overwrites the first one
console.log (firstName); // Bob
Another example
// 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
// The use of the "this" object inside the setTimeout function refers to the Window object, not to myObj
// 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.
// 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";
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).
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
// 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");
}
It is important to note that function expressions, such as the example below, are not hoisted.
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.
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.
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
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() {
});
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:
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
// 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;
}
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
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:
return theCelebrities;
}
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.
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.
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.
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.
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)
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;
}
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.
This sounds way more complex that it is, so let’s take a closer look.
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:
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.
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.
//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:
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:
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.
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
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:
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:
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
__________
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 .
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:
$(function () {
var shoesData = [{name:"Nike", price:199.00 }, {name:"Loafers", price:59.00 }, {name:"Wing Tip", price:259.00 }];
function updateAllShoes(shoes) {
var theHTMLListOfShoes = "";
});
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.
1. Changes to index.html:
Add this code just below the closing ul tag
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();
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.
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):
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:
Comments
This is how you add comments in a Handlebars template:
And you can also use regular HTML comments, but they will be outputted on the HTML page source, as HTML comments of course:
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 {{/ }}.
Here is an if block
The words block and helper are sometimes used interchangeably because most built-in helpers are blocks, although there are function helpers and block
helpers.
We can use nested paths (dot notation) to lookup the property you want, like this:
{{name.firstName}}
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>
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:
2. Add this new template for the description; add it just below the shoe-template:
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.
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:
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:
As opposed to this:
Since the evaluated expression from the data will be just the object, we use the this keyword:
{{#each this}}
<li>{{firstName}} {{lastName}} </li>
{{/each}}
{{#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>
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>
We can use the with block to target the groupName property where we need access to its values:
The with block is probably one that you will rarely use.
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.
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.
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
});
Here is the Handlebars template that uses the custom function helper we just created:
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:
// 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
// We return the full string of HTML with all the values from the data object inserted into place.
return templateWithInterpolatedData;
});
— 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.
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:
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.
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
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.
// 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);
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
References
1. http://handlebarsjs.com/
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.
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.
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.
if (userName) {
logIn (userName);
}
else {
signUp ();
}
Use this:
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:
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.
(function () {
// Do fun stuff
}
)()
It is an anonymous function expression that is immediately invoked, and it has some particularly important uses in JavaScript.
It is as if we have this:
// Shown without the parentheses here:
? = function () {};
— 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
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:
function doStuff () {
// Do stuff here
}
function doMoreStuff () {
// Do more stuff here
}
— Note that you can also pass jQuery or any other object or variable via the parameter (the last 2 parentheses).
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
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:
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;
}
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
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.
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.
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
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.
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.
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.
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.
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.
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.
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.
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.
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.
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
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
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
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
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.
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.
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.
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.
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 ;).
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.
//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.
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.
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:
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.
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.
// global variable
var allUserData = [];
// A function that takes two parameters, the last one a callback function
function getInput (options, callback) {
allUserData.push (options);
callback (options);
//Global variable
var generalLastName = "Clinton";
Let’s refactor the getInput function from the previous example to ensure these checks are in place.
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.
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:
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.
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);
We would have also used the Call function, but in this case we used the Apply 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
});
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:
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.
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;
Call the getUserInput function and pass the genericPoemMaker function as a callback:
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:
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)
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.
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:
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.
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;
}
}
// A User
firstUser = new User("Richard", "[email protected]");
firstUser.changeEmail("[email protected]");
firstUser.saveScore(15);
firstUser.saveScore(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
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;
};
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;
}
// A User
firstUser = new User("Richard", "[email protected]");
firstUser.changeEmail("[email protected]");
firstUser.saveScore(15);
firstUser.saveScore(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.
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.
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:
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:
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.
//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;
}
// 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!) *****
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 function is the parent for all other question objects;
// All question objects will inherit from this Question constructor
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);
};
And then we have to use the inheritPrototype function we discussed moments ago:
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.
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:
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:
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)
];
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.
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.
(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
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
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.
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:
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.
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:
Day 2
Part 2
In a follow post, we will learn Advanced HTML5 for Modern Web Application Development.
The topics will include:
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
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
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.
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);
}
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
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.
Thus:
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);
}
}
// 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
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
// 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
// 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);
}
}
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.
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:
$ ("button").click (user.clickHandler);
We have to bind the clickHandler method to the user object like this:
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 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.
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.
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);
}
// 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)
// Now we get the value from the user object, because the this keyword is bound to the user object
showUserData (); // P. Mickelson 43
// 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 () {
// 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.
// 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.
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.
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:
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)
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.
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);
}
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:
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:
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:
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
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:
// Now the we get the value from the user object because the this keyword is bound to the user object
showDataVar (); // P. Mickelson 43
// 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
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.
Let's use the bind () method for currying. First we have a simple greet () function that accepts 3 parameters:
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);
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.
Here is a very quick, illustrative example for starters before we get into more complex usages of Apply and Call:
//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
// To set the "this" value explicitly, so that "this" is bound to the gameController,
// We use the call () method:
avg.call (gameController, gameController.scores);
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.
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.
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:
Now, if wish to use any of the common Array methods on our object, we can:
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
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:
// 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);
}
We will discuss how to use the apply method with the arguments array-like object again for variadic functions. More on this later.
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 () {
// 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
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);
}
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).
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:
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.
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:
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"];
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.
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
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.
$("#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.
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();
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
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.
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.
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.
file:///Users/shafiultareq/Downloads/JavaScript%20is%20Super%20Sexy%20%7C%20JavaScript%20is%20Sexy.html Page 60 of 60