I create mousemade pixel perfection stuffs for the interwebs.

Published: 7 years ago

Javascript journey – The differences

So I am diving into the real JavaScript i.e. more than DOM manipulation using jQuery. As it is used for creating Windows 8 apps, cross platform mobile apps (using Appcelerator Titanium) and even on server side (via Node.js), understanding the JavaScript thoroughly is a requirement. I believe this is the language of future, where performance is handled by better processors.

I knew only basic javascript (jQuery based DOM manipulation). So when I decided to start learning Node.js, I could not make head & tail out of its’ asynchronous nature. Then I started reading about JavaScript in more detail. As recommended by many, I started studying Javascript: The Good Parts.

Here are some aspects of JavaScript which confused me. I may add more when I encounter more.

1. Functions can return functions, and variables may be functions

var something = function(arg1, arg2){
    //Do something

And, then you can return a function from a function.

function somefunction(arg1){
    //Do something with arg1
    return function(arg2){
         //Do something with arg1 and arg2

2. Closures

While it was relatively easy for me to understand global and local scopes, closures were completely new to me.

Inner functions referring to local variables of its outer function create closures.

OK. What does that mean, in practice?

function add(x){
    return function(y){
        return x+y;
var add10 = add(10)
var added10to8 = add10(8)

Here, when add is called with argument x, it returns a function, which can accept another argument. This returned function remembers the value of x. This is what makes it a closure.

I was surprised this did not work as expected:

for (var i = 0; i < 5; i++) {
    setTimeout(function () {
    }, i*500);

I expected it to output

 0 1 2 

But it output

 2 2 2 


Apparently first the loop is run thrice, and the value of i is now 2. Then setTimeout is run thrice, and as i is 2, it outputs 2 thrice.

Again, Why?

Because setTimeout ques operation for execution. It is not run simultaneously. So it refers to the latest value of i, which is 2.

How do we make it work?

Solution: Add a closure around setTimeout, so that it gets right value.

for (var i = 0; i < 5; i++) {
    (function (i) {setTimeout(function () {
         console.log(i); }, i*500); 

Here, we create an anonymous function which accepts a parameter i. Then we immediately invoke it with current value of i. This creates a closure.

What happened is, this anonymous function is called 3 times with different values fori. On each call, setTimeout gets called with respective values.

We define and invoke anonymous function like this:

(function(args_to_accept){ //statements } ) (args_to_pass)

Leave a Reply

Some HTML is OK