Understanding ES2015 In Depth, Part 1: Block Scope with let and const

»feb. 1 This Year

About the ES2015 Series

This series, Understanding ES2015 In Depth, will give you a thorough understanding of some of the most recent additions to ECMAScript, the scripting language also known as JavaScript, which powers the modern Internet as we know and love it.

About the Author

Dan Wellman is an author and web developer from the UK. He’s written nine books on using JavaScript frameworks and libraries including YUI, jQuery, and jQuery UI, and is a regular contributor to Envato’s Tuts+ code courses. He is also Lead Front-End Developer at Bluedoor DST and Curriculum Director at Bov Academy of Programming, where he has written the highly acclaimed course Becoming a JavaScript Expert.

Dan has previously worked as a Front-End Engineer at Microsoft.

About this Post

This post, Block Scope with let and const, lays the foundation of your ES2015 knowledge by giving you a solid foundation in the fundamentals of the different scopes available in JavaScript, the different scenarios that cause scopes to be created, and the impact this has on variable access.

Prerequisites:

  • None

Reading time: 15 minutes
Author: Dan Wellman

One of the major features introduced by ES2015 is a whole new scope. In this section, we’re going to start by learning what a scope is. We’ll then move on to look at how we can create the new type of scope, and the benefits it can bring to our code.

A Quick Introduction to Scope

The term scope describes an area in which variables and functions, or identifiers, can be accessed. JavaScript has traditionally had two types of scope: global scope and function scope, and the place in your code in which a variable is declared affects whether it can be accessed by other parts of your code. Let’s look at an example with some code to illustrate the concept of scope. Imagine that you have a JavaScript file containing only the following code:

var globalVariable = 'This is global';

function globalFunction1() {
  var innerVariable1 = 'Non-global variable 1';
}

function globalFunction2() {
  var innerVariable2 = 'Non-global variable 2';
}

In the above code we first declare globalVariable. This statement is not inside a function so this variable will automatically be stored in the global scope. The browser creates the global scope, using the window object, so as well as accessing the variable using the identifier globalVariable, we could also access it through the window object using window.globalVariable. We can access this variable anywhere in the file, before or after the two functions, and even inside them, which is why we say that global variables are “visible” to all of our code—we can literally access them from anywhere, even in other JavaScript files attached to the same page.

Following the global variable we declare two functions, globalFunction1 and globalFunction2, like the global variable, these function can be “seen” and invoked by code anywhere else in this file, or in other files loaded by the same page. However, when the JavaScript engine parses these functions, it will create two new function scopes, one for each of the functions. This is where things get interesting; scopes in JavaScript are nested so the two new function scopes become child scopes of the global scope. This means that the code inside each function can access the global globalVariable variable, as if it had been declared inside the function alongside the inner variables.

When trying to access an identifier in JavaScript, the browser will first look for the variable inside the current scope. If it is not found, the browser will then look in the parent scope of the current scope, and will keep moving up through the parent scopes until it either finds the variable, or reaches the global scope. If the variable still isn’t found in the global scope, the browser will generate a ReferenceError. The nested scopes are known as a scope chain, and this process of checking the current scope and then the parent scopes is known as a variable look-up. This look-up is only able to go up the scope chain, it will never look inside child scopes of the current scope.

What the direction of the look-up through the scope chain means for the above example is that innerVariable1 can only be accessed inside the globalFunction1 function, and innerVariable2 can only be accessed inside the globalFunction2 function. innerVariable1 cannot be accessed within the globalFunction2 function, or by the global scope, and innerVariable2 cannot be accessed by globalFunction1 or the global scope.

The following image shows an abstract representation of the scopes in the above code:

The global scope contains the nested function scopes

The global scope contains the globalVariable as well as the two nested function scopes. Each nested function scope contains its own variable, but these variables are not accessible to the global scope. The dotted lines represent the direction of the look-up through the scope chain.

Let’s look at another brief code example to hammer home the scope concepts that we’ve covered so far. Consider a JavaScript file which contains only the following code:

function outer() {
  var variable1;

  function inner() {
    var variable2;
  }
}

In this code, we have an outer function named outer, which is defined in the global scope. As it’s a function, it creates a function scope which is nested within the global scope. Inside this scope we declare the variable variable1 and a new function called inner. As inner is also a function, a new scope is created, and nested within the outer function’s scope.

Inside the inner function, we can access both variable2—which is in the inner function’s scope—and variable1. When we access variable1 from inside the inner function, the browser will first look for the variable in its current scope; when the variable is not found, the look-up will navigate up to the parent scope, which is the outer function’s scope. The scopes in this code could be represented like this:

This image shows a function scope nested within another function scope, nested inside the global scope

Function scopes may be nested within other function scopes, but the same rules around the scope-chain look-up apply, so the inner scope can access both variable1 and variable2, but the outer scope can only access variable1.

The scope chain is longer in this example, stretching from the inner function, through the outer function, and up to the global window object.

JavaScript’s New Scope

In JavaScript, a block is one or more statements within curly brackets. Conditional expressions, such as if, for, and while statements, all use blocks to execute statements based on certain conditions.

Other popular and common programming languages have block scope, so scope in JavaScript, which until now has only had global and function scope, has always been considered confusing. The ES2015 addition of block scope to JavaScript has important implications for our code and can also make the language more intuitive to developers familiar with other programming languages.

Block scope means that a block is able to create its own scope, rather than simply existing within the scope created by its nearest parent function, or the global scope. Let’s take a quick look at how scope has traditionally worked with blocks in JavaScript before we move on to look at how block scope now works:

function fn() {
  var x = 'function scope';

  if (true) {
    var y = 'not block scope';
  }

  function innerFn() {
    console.log(x, y); // function scope not block scope
  }
  innerFn();
}

The var statement is not able to create a block scope, even when used within a block, so the console.log statement is able to access both the x and y variables. The fn function creates a function scope and both the x and y variables are accessible via the scope chain within that scope.

Hoisting

Understanding the concept of hoisting is fundamental to understanding how JavaScript works. JavaScript has two phases: a parsing phase—where all of the code is read by the JavaScript engine—followed by an execution phase in which the code that has been parsed is executed. It is during this second phase that most things happen; for example, when you use a console.log statement, the actual log message is printed to the console during the execution phase.

However, some important things happen during the parsing phase as well, including memory allocation for variables and scope creation. The term hoisting describes what happens when the JavaScript engine encounters an identifier, such as a variable or function declaration; when it does this, it acts as if it literally lifts (hoists) that declaration up to the top of the current scope. In light of this, in the above code example, what really happens is this:

function fn() {
  var x;
  var y;

  x = 'function scope';

  if (true) {
    y = 'not block scope';
  }

  function innerFn() {
    console.log(x, y); // function scope not block scope
  }
  innerFn();
}

Only the variable declaration is hoisted to the top of its scope; the variable assignment still occurs at the place where we assigned the value, inside the if statement in this example. Of course, our variables aren’t literally moved around in our code, but the engine behaves as if this is what happens, so this is a useful device for understanding our code better.

In addition to variables, function declarations are also hoisted. Consequently, from the JavaScript engine’s perspective, the code actually looks like this:

function fn() {
  var x;
  var y;
  function innerFn() {
    console.log(x, y); // function scope not block scope
  }

  x = 'function scope';

  if (true) {
    y = 'not block scope';
  }
  innerFn();
}

The declaration of innerFn is also moved to the top of its scope. But remember, it is just the declaration of the function that is hoisted, not the invocation of the function. The above code won’t throw any errors because innerFn isn’t invoked until after the x and y variables have had values assigned to them.

Using let

Even when using ES2015, the var statement does not create block scope. In order to create block scope, we need to use either the let or const statements inside a block. We’ll come back to const shortly. For now, let’s focus on let.

Superficially, let is very similar to var—we use it to declare variables:

function fn() {
  var variable1;
  let variable2;
}

In this simple example, the var and let statements both do the same thing—they initialise a new variable in the current scope, which is the scope created by the fn function. In order to create a new block scope, we need to use let inside a block:

function fn() {
  var variable1 = 'function scope';

  if (true) {
    let variable2 = 'block scope';
  }

  console.log(variable1, variable2); // Uncaught ReferenceError: variable2 is not defined
}
fn();

In this case the code throws a reference error; let’s explore why. The fn function creates a new scope within which variable1 is declared. We then have an if statement, which uses a block to declare variable2. However, because we used the let statement within that block, a new block scope is created within the fn scope.

If the console.log statement had been inside the if block as well, it would be in the same scope as variable2 and would be able to use the scope chain to find variable1. But because console.log is in the outer fn scope, it can’t access variable2, so it throws a reference error.

Block scopes work the same as function scopes work, but they are created for blocks, rather than functions.

The Temporal Dead Zone

When a regular variable created using var is hoisted to the top of its scope, it’s initialized with the value undefined, which is what allows us to be able to reference a normal variable before it has a value declared through assignment:

console.log(x); // undefined
var x = 10;

Remember, because of hoisting, the code is actually understood as this:

var x = undefined;
console.log(x); // undefined
x = 10;

This behavior prevents a ReferenceError from being thrown.

Variables declared with let are hoisted, but crucially, they are not automatically initialised with the value undefined, which means that the following code produces an error:

console.log(x); // Uncaught ReferenceError: x is not defined
let x = 10;

This error is caused by the temporal dead zone (TDZ). The TDZ exists from the moment the scope is initialized to the moment the variable is declared. To fix the ReferenceError, we need to declare the variable before trying to access it:

let x;
console.log(x); // undefined
x = 10;

The TDZ was designed like this in order to make development easier—trying to reference a variable that has not been declared yet is more commonly an error than an intentional decision, so the error highlights this to us immediately.

Using const

The new const statement is used to declare a variable whose value cannot be reassigned. It behaves in a very similar way as let does with regard to the TDZ, but when being declared, a const variable must be initialised with a value:

const VAR1 = 'constant';

From this point on, the value of VAR1 will always be the string constant. If we try to change the value of the variable through reassignment, we’ll see an error:

TypeError: Assignment to constant variable

If we try to create a const variable without initializing it with a value, we’ll also see an error; this time a SyntaxError:

SyntaxError: Missing initializer in const declaration

Simirlarly, a const variable cannot be redeclared. If we try to declare the same const variable more than once, we’ll see a different type of SyntaxError:

SyntaxError: Identifier ‘VAR1′ has already been declared

As with other programming languages, constants are useful for holding values that we do not expect to change over the life of our program.

It is important to note that let and const are both reserved words in JavaScript, and so cannot be used as identifier names in strict mode. As ES2015 becomes more and more common, a consensus is emerging that both let and const are superior to var because the scope of variables created with them is more aligned to other modern programming languages, and code behaves in a much more predictable way. Therefore, for most situations it is preferable to avoid the use of var if possible.

Immutability

While the value of a const variable cannot be changed with reassignment, const variables are not completely immutable. If we initialize a const variable with an object or an array, we will still be able to set the properties of the object and add and remove items to the array.

Exercises

  1. Use let to initialize the counter variable for a for loop.
  2. Fix the following const errors:
    • const VAR1 = 'constant';
      const VAR1 = 'constant2';
    • const VAR2;
      VAR2 = 'constant';

Learn Meteor.js Properly

»oct. 9 2014 112

(Learn Meteor and Everything You Need to Know about It)

At the end of this article, I outline two comprehensive study guides to help you learn Meteor properly. The study guides are for both beginners and seasoned developers. The first study guide, which uses a book, a paid screencast, and some free online resources, teaches you how to build a sophisticated, modern social-media web application with Meteor. And the second study guide, which uses only free resources (one affordable screencast and free online resources), is just as instructive as the first, though you won’t build a specific web application throughout the course.

Become an Elite/Highly Paid Specialized Software Engineer (Frontend, Fullstack, etc.)

Within 8–10 Months, Earn MORE than the Avg. New CS Graduate Earns.

New Prices (Monthly Subscription):
Basic: $250/month, Pro: $350/month, Premium: $600/month

By the founder of JavaScriptIsSexy

First, I give a comprehensive Meteor overview, in which I discuss just about everything you want and need to know about Meteor before you commit to investing your time and other resources in this still burgeoning though exceptional technology.

Time to read the Meteor Overview:

14 minutes 


What You Will Learn in this Meteor Overview

I explain exactly what Meteor is, how it differs from typical JavaScript frameworks, what it offers developers specifically, its alternatives and contemporaries, whether you should be excited or skeptical about it, and where to find Meteor jobs. I also enumerate some of the endorsements written by Meteor converts, and I explore the justifiable criticisms, known limitations, and frequently asked questions that many have raised about Meteor. You will learn all this and much more.

I am honored that you have joined me and I am hopeful you will find this article helpful and illuminating and the accompanying study guides and recommended resources sufficiently instructive. If you don’t, then I would have failed and I would like to hear from you; please notify me in the comments below. Don’t hesitate to alert me of any grammatical errors, typos, general errors, misinformation, missing information, outdated content, or incomprehensible sentences or passages. You won’t hurt my feelings, for I am most interested in providing you accurate, clear, and comprehensible material, and only you can determine whether I have done that.

Learn Meteor Properly Study Group

People have already started study groups for this study guide. One study group starting today (November 3) on Facebook already has over 100 members. You can also find the group on Reddit.

If you want to start a study group, send me Tweet or an email.

  • Receive Updates

Let’s begin with a comprehensive overview of Meteor.

How Will Your Life Change After You Learn Meteor Properly?

No, you won’t be cleansed of your sins and washed of your immoralities after learning Meteor properly. Neither will you lose five pounds nor grow two inches.

However, if you have never developed any kind of application before, you will experience ecstasy, so powerful and liberating it will free you to envision, build, and realize your imaginations, like an artist discovering paint and canvas for the first time.

If you currently use Meteor (and even if you have read a Meteor book or some tutorials), you will emerge better equipped to understand and handle common Meteor errors and the often-misunderstood Meteor “magic,” allowing you to experience Meteor’s true efficacy. Efficient, productive, painless.

If you use Rails, Node.js, PHP, Django, Go, Scala, or Java, you will understand Meteorites’ (i.e., Meteor developers) unapologetic praise for Meteor. You wouldn’t be convinced that every facet of Meteor is better than every facet of Rails or Django (it isn’t) or that Meteor will kill Rails or Python (it won’t). But you will undoubtedly acknowledge and appreciate, even if reluctantly, the efficiency and painlessness Meteor affords, as well as its effectiveness in making you a more productive developer—indeed, a happier developer. But be careful, my friend, for even a faithful developer can be tempted by seduction, lured by betterment, and give in to pleasure.

If you currently use proven but old-school technologies to develop applications, learning Meteor properly will allow you to experience the current state of modern web application development. This will prepare you for the foreboding robotic and futuristic frameworks that will inevitably evolve out of technologies like Meteor. You will therefore become familiar with the latest, experience the now, and embrace the inevitable.

Or, if after learning Meteor properly you remain unmoved, unconvinced, or unimpressed, then we would love to hear from you. For you may have invaluable information about efficient web-development tools that we can all use.
Continue Reading

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

»aug. 13 2013 30

(Part of the “12 Powerful JavaScript Tips” Series)

Prerequisites:
Understand JavaScript’s “this” With Ease
JavaScript Objects in Detail

Chaining Methods, also known as Cascading, refers to repeatedly calling one method after another on an object, in one continuous line of code. This technique abounds in jQuery and other JavaScript libraries and it is even common in some JavaScript native methods.

Become an Elite/Highly Paid Specialized Software Engineer (Frontend, Fullstack, etc.)

Within 8–10 Months, Earn MORE than the Avg. New CS Graduate Earns.

New Prices (Monthly Subscription):
Basic: $250/month, Pro: $350/month, Premium: $600/month

By the founder of JavaScriptIsSexy

Writing code like this:

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

or this:

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

is not just pleasurable and convenient but also succinct and intelligible. It allows us to read code like a sentence, flowing gracefully across the page. It also frees us from the monotonous, blocky structures we usually construct.

  • Receive Updates

We will spend the next 20 minutes learning to create expressive code using this cascading technique. To use cascading, we have to return this (the object we want subsequent methods to operate on) in each method. Let’s quickly learn the details and get back to eating, or watching YouTube videos, or reading Hacker News, or working and browsing, or working and focusing.

Let’s create all of our “chainable” code within an object, along with a local data store. Note that in a real-world app we will likely store the data in a database, but here we are just saving it in a variable.

 // The data store:
var usersData = [
    {firstName: "tommy", lastName: "MalCom", email: "test@test.com", id: 102},
    {firstName: "Peter", lastName: "breCht", email: "test2@test2.com", id: 103},
    {firstName: "RoHan", lastName: "sahu", email: "test3@test3.com", id: 104}
];


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


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

    currentUser: "",

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

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

    },

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

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

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

    }
};

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

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

»july. 10 2013 103

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

Duration: About 40 minutes.

Become an Elite/Highly Paid Specialized Software Engineer (Frontend, Fullstack, etc.)

Within 8–10 Months, Earn MORE than the Avg. New CS Graduate Earns.

New Prices (Monthly Subscription):
Basic: $250/month, Pro: $350/month, Premium: $600/month

By the founder of JavaScriptIsSexy

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

  • Receive Updates

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

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

16 JavaScript Concepts JavaScript Professionals Must Know Well

»july. 9 2013 62

(Essential JavaScript Concepts for Modern JavaScript Development )

If you plan to work as JavaScript Professional, you must know some JavaScript concepts and JavaScript-related web-development technologies, particularly as a modern JavaScript developer. If you know the 16 concepts enumerated below, you have the skill necessary to build world-class modern JavaScript web applications, and you are set for the near future—0 to 3 years.

Become an Elite/Highly Paid Specialized Software Engineer (Frontend, Fullstack, etc.)

Within 8–10 Months, Earn MORE than the Avg. New CS Graduate Earns.

New Prices (Monthly Subscription):
Basic: $250/month, Pro: $350/month, Premium: $600/month

By the founder of JavaScriptIsSexy

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 for the newsletter to get the latest updates.

  • Receive 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 note below are neither complex nor difficult, you will understand them best if you already know at least some basic JavaScript.

The sixteen concepts that every modern JavaScript developer should know well follow:

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

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

»july. 5 2013 190

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

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

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

Become an Elite/Highly Paid Specialized Software Engineer (Frontend, Fullstack, etc.)

Within 8–10 Months, Earn MORE than the Avg. New CS Graduate Earns.

New Prices (Monthly Subscription):
Basic: $250/month, Pro: $350/month, Premium: $600/month

By the founder of JavaScriptIsSexy

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

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

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

  • Receive Updates


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

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

JavaScript’s this Keyword Basics

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

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

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

»may. 6 2013 72

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

Become an Elite/Highly Paid Specialized Software Engineer (Frontend, Fullstack, etc.)

Within 8–10 Months, Earn MORE than the Avg. New CS Graduate Earns.

New Prices (Monthly Subscription):
Basic: $250/month, Pro: $350/month, Premium: $600/month

By the founder of JavaScriptIsSexy

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

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

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

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

What You Will Learn?

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

Continue Reading

OOP In JavaScript: What You NEED to Know

»march. 19 2013 217

(Object Oriented JavaScript: Only Two Techniques Matter)

Become an Elite/Highly Paid Specialized Software Engineer (Frontend, Fullstack, etc.)

Within 8–10 Months, Earn MORE than the Avg. New CS Graduate Earns.

New Prices (Monthly Subscription):
Basic: $250/month, Pro: $350/month, Premium: $600/month

By the founder of JavaScriptIsSexy

Prerequisite:
JavaScript Objects in Detail
JavaScript Prototype

Object Oriented Programming (OOP) refers to using self-contained pieces of code to develop applications. We call these self-contained pieces of code objects, better known as Classes in most OOP programming languages and Functions in JavaScript. We use objects as building blocks for our applications. Building applications with objects allows us to adopt some valuable techniques, namely, 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 concerned with only Inheritance and Encapsulation since only these two concepts apply to OOP in JavaScript, particularly because, in JavaScript, objects can encapsulate functionalities and inherit methods and properties from other objects. Accordingly, in the rest of the article, I discuss everything you need to know about using objects in JavaScript in an object oriented manner—with inheritance and encapsulation—to easily reuse code and abstract functionalities into specialized objects.

  • Receive Updates

We will focus on only the best two techniques1 for implementing OOP in JavaScript. Indeed, many techniques exist for implementing OOP in JavaScript, but rather than evaluate each, I choose to focus on the two best techniques: the best technique for creating objects with specialized functionalities (aka Encapsulation) and the best technique for reusing code (aka Inheritance). By “best” I mean the most apt, the most efficient, the most robust.

Continue Reading

Understand JavaScript Callback Functions and Use Them

»march. 4 2013 192

(Learn JavaScript Higher-order Functions, aka Callback Functions)

In JavaScript, functions are first-class objects; that is, functions are of the type Object and they can be used in a first-class manner like any other object (String, Array, Number, etc.) since they are in fact objects themselves. They can be “stored in variables, passed as arguments to functions, created within functions, and returned from functions”1.

Become an Elite/Highly Paid Specialized Software Engineer (Frontend, Fullstack, etc.)

Within 8–10 Months, Earn MORE than the Avg. New CS Graduate Earns.

New Prices (Monthly Subscription):
Basic: $250/month, Pro: $350/month, Premium: $600/month

By the founder of JavaScriptIsSexy

  • Receive Updates

Because functions are first-class objects, we can pass a function as an argument in another function and later execute that passed-in function or even return it to be executed later. This is the essence of using callback functions in JavaScript. In the rest of this article we will learn everything about JavaScript callback functions. Callback functions are probably the most widely used functional programming technique in JavaScript, and you can find them in just about every piece of JavaScript and jQuery code, yet they remain mysterious to many JavaScript developers. The mystery will be no more, by the time you finish reading this article.

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

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

Learn Intermediate and Advanced JavaScript

»feb. 25 2013 26

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

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

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

Duration:
2 Weeks

Become an Elite/Highly Paid Specialized Software Engineer (Frontend, Fullstack, etc.)

Within 8–10 Months, Earn MORE than the Avg. New CS Graduate Earns.

New Prices (Monthly Subscription):
Basic: $250/month, Pro: $350/month, Premium: $600/month

By the founder of JavaScriptIsSexy


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

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