Ashish Dasnurkar


demystifying the javascript closure

Imagine you are a mexican cook in the middle of an imaginary mexican desert. Your job is to cook whenever you are called upon. For you to be able to cook something, you need access to some usual stuff like ingredients, utensils and fire. Of course if you are in the middle of an imaginary desert you won’t have anything on you or have access to anything. So let’s also give you some super power, maybe flexible, stretchable, unbreakable arms that can reach to any cornerspart of the earth to retrieve whatever you need.

Different ways of invoking JavaScript functions

In JavaScript the way a function is invoked has a significant impact on how the code within it executes, especially regarding this parameter. If you have followed couple of my earlier posts I have demonstrated two ways of invoking functions already and they are 1. Invoking functions as, surprise, functions 2. Invoking functions as object methods Now in addition to these two there are two more ways of invocations 3. Invoking functions as constructors 4.

JavaScript scopes

I started my programming career with C,C++/VC++ and then Java. All are known as C family languages and they all share block level scope when it comes to variables and function declarations. In other words each block, typically represented by { and } braces, creates a new scope. For e.g. #include <studio.h> int main() { int a = 1; printf("%d ", a); //1 if(1) { int a = 2; printf("%d ", a); //2 } printf("%d ", a); //1 } Scope of int avariable declared inside ifblock exists only till the end of ifblock.

JavaScript functions travel first class

Functions in JavaScript are first class citizens of the language just like Objects. In another words Functions enjoy all the same privileges (in fact more) as do the Objects in JavaScript. Privileges such as 1. Functions can be created via a literal. var obj = {a : 2, b: 2}; // object literal var add = function(a, b) { // function literal return a + b; }; 2.