Saturday 23 August 2014

Javascript - "this" is it.....

In this blog post we will take up one of the most interesting topic in Javascript. Please read this blog post with caution as it comes with a disclaimer.

"this" blew my brains out.......

For all of those like me who are coming to Javascript from any 4G language would know that this refers to the current instance of the object. So say we have a class Employee and we created its instance _employee, now inside any function defined in Employee this will refer to the current instance(_employee).

Well lets say in terms of Javascript above statement is only a part of the truth. In Javascript this is refers to much more. To begin with it this inside a function refers to the object which invoked the function where this is used.

So lets try to make sense of above statement, fire up the chrome console and emit out following snippet.
var person = {
    firstName: 'Bond',
    lastName: 'James',
    showName: function () {
        console.log('Name is ' + this.firstName + ' ' + this.lastName + ' ' + this.firstName);
    }
}
person.showName();//Name is Bond James Bond

1st Golden Rule:
this refers to the value of the object that invoked the function using this

In the example above person invoked the function (showName) and thus this inside showName points to person.

firstName = 'Alpha';
lastName = 'Beta';

 var person = {
     firstName: 'Bond',
     lastName: 'James',
     showName: function () {
         console.log('Name is ' + this.firstName + ' ' + this.lastName + ' ' + this.firstName);
     }
 }

 //called in context of person
 var callfunc = person.showName(); //Name is Bond James Bond


 function showName() {
     console.log('Name is ' + this.firstName + ' ' + this.lastName + ' ' + this.firstName);
 }

 //called function from global context
 showName(); //Name is Alpha Beta Alpha


2nd Golden Rule
this of outer function is not accessible to inner function (for that matter both this and argument of outer function are not accessible to the inner function), it basically points to the global object

var name="pankaj";
var outer={
    name:"lala",
    getNameFunc : function(){
        return function(){
            return this.name;
        };
    },
    getFunc : function(){
        return this.name;
    }
};
   
console.log(outer.getNameFunc()()); //pankaj
console.log(outer.getFunc());     //lala

A bit confusing thus deserve a bit of explanation. Since getNameFunc was invoked with reference to outer we would expect this inside of getNameFunc to refer to outer only and thus lala should be available to same.

Unfortunately this is one of those things in Javascript which is let’s say interesting. I remember getting into discussion with one of my peer if this is a feature of Javascript of behaviour the debate got all heated up until Douglas Crockford came to my rescue.

In his book Javascript the good parts he did mentions that this is a mistake in design of the language, had the language been designed correctly, when the inner function is invoked, this would still be bound to the this variable of the outer function.

A very common workaround for correcting this behaviour is to preserve this of outer function and in the inner function use same instead of this. Doing this will ensure that in which ever context the call is made inner function will always refer to the context of the outer function.

var name="pankaj";
var outer={
    name:"lala",
    getNameFunc : function(){
       var that = this;
        return function(){
            return that.name;
        };
    },
    getFunc : function(){
        return this.name;
    }
};
   
console.log(outer.getNameFunc()()); //pankaj
console.log(outer.getFunc());     //lala

I will explain later why as per me this is a workaround.



Its worth mentioning that a function which is part of an object (which again is a function), it known as the method of the object

3rd Golden Rule

When a method is assigned to a variable, this belongs to the global context

var name ='Pankaj';

var Person ={
    name:'Lala',
    getName: function(){
        return this.name;
    }
}

//getName invoked within context of Person
console.log(Person.getName()); //Lala

//capture the reference of getName in local var
var func = Person.getName;

// getName gets invoked with the context of global
console.log(func()); // Pankaj


4th Golden Rule

For borrowed method, this belongs to the new object

var SimpleCaclulator={
    num1:5,
    num2:5
}

var ComplexCalculator={

    num1:10,
    num2:20,
    add:function(){
        return this.num1+ this.num2;
    }
}

console.log(ComplexCalculator.add()); //30
SimpleCaclulator.add = ComplexCalculator.add; // attching add to SimpleCaclulator
console.log(SimpleCaclulator.add());    // 10 this belongs to SimpleCaclulator

Summary
These sums up the quirks with this in Javascript. We looked at what this means in Javascript, how it should be used. 

We also learned the workaround to avoid falling into these quirks, to mention in coming posts we should be taking about the standard ways to avoid these situations. 

Till then 'this' is it.

Friday 15 August 2014

Execution Context - The Twin Towers


To recap our last post we learned that Execution Context is bundled of
  • Variable Object
  • Scope
  • this
In this post we take up the twin towers of Execution context, namely Variable object and Scope.

Variable\Activation object

When EC is being created Javascript interpreter first scans (before executing) the functions for all arguments passed, variables in the function and function declaration in the function.

It then initializes the Variable object with:
  • arguments passed, it scans the context and initializes the variable's name & its values and create a reference copy.
  • for each function in the context create a property (with name as that of function) in the function. If there are two functions with different name the latter will override the previous one.
  • for each variable declared in the context create a named property in the Variable object. Initialize these variables with undefined.If another variable with same name found, do nothing.
  • function declaration will override variable initialization but not variable declaration.
Once the variable object is defined then the interpreter starts initializing it, this happens during the execution of the function.

Lets consider a following example
         function Sample(val1,val2){

         var name = val1;
         var age = val2;
         var count=1;
        var getName = function(){
           //
        };
    
        function incrementAge(){
          //
       }
}

Sample('Hulk',999);

During the defining phase Variable object looks like
arguments:{
  0: 'Hulk',
  1: 999,
  length:2
},
val1:'Hulk',
val2:999,
name:undefined,
age:undefind,
count:undefined,
getName: undefined
incrementAge: pointer to function incrementAge()


When Sample('Hulk',999) is called then during the initializing phase

arguments:{
  0: 'Hulk',
  1: 999,
  length:2
},
val1:'Hulk',
val2:999,
name:'Hulk',
age:999,
count:1
getName: pointer to function getName()
incrementAge: pointer to function incrementAge()

So by now you are aware of how the Variable object looks like. Now lets see how we can understand one of the core concept of Javascript called Hoisting.


Hoisting

Lets look at this example:

function foo(){
if(!a){
var a=10;
}

console.log(a);
}
foo(); //10

Its easy to explain that during the defining phase Variable object will create the variable a with undefined value, thus if condition is always true and thus the value is 10. We can confirm same by

function foo(){
console.log(a); //undefined
if(!a){
var a=10;

console.log(a);//10
}
foo();

Lets consider another example

function foo(){
    var b
    function b(){}
    console.log(b);  //[Function: b]
                              //Function declaration overrides variable initialization but not variable declaration
}
foo();

However if we modify above like

function foo(){
    var b =5
    function b(){}
    console.log(b); //5
}
foo();

Thus we see that hoisting creates some interesting (hmm..) moments

Scope

Lets take a look at this picture again


Recall that Scope is the chain of Variable objects for current EC and all the parent EC. Before digging up further lets first get our self familiarize with something called as Lexical Scope.


Lexical Scope

I have to be honest understanding lexical scoping was among the most difficult concept I had to understand and what made it worst was during my exploration I came to know that C# is also Lexical scope language.




Instead of me blabbering about type of scope in programming languages let me take the snippet out from Eric Lippert's blog 

Programming languages can be broadly divided into two categories: the lexically scoped languages and the dynamically scoped languages. The difference between the two is: in a lexically scoped language, the meaning of an unqualified name can be completely determined by looking at the program text; the analysis can be done “statically”. In a dynamically scoped language the meaning of an unqualified name can change at runtime; the name analysis can only be done “dynamically”.

Take a look at following example 
function foo(){
var x=45;
var val =goo();
console.log(val());
}

function goo(){
var x =100;
return function (){return x;};
}

foo(); //100

Since variable x will be resolved statically (meaning looking at the text) even though it appears that goo() is called with the context having x as 45, it is actually bound to the EC of goo() when it was parsed.

It gets more interesting when the function is an inner one, remember that every time a function is invoked a new EC is created (read new variable object, scope & this).

This is a classical example

var myarray=[];

for (var i=0;i<5;i++){
myarray.push(
function func(){
console.log(i);
}
);
}

for(var c=0;c<myarray.length;c++){
myarray[0]();
}

This print value 5 every time! 
I will try to explain what happened here here the variable object for EC of window contains 
myarray
i
func

when we iterate and add the func to myarray, each func gets bounded with i (defined in global context). Now when we execute the func its scope  (which is scope of the window) tries to resolve i, which by the end of the iteration has already become 5.

To verify same lets use the variable i instead of c in the second loop by doing that we are re-initializing the variable i and the value will be printed accordingly.

var myarray=[];

for (var i=0;i<5;i++){
myarray.push(
function func(){
console.log(i);
}
);
}

for(var i=10;i<15;i++){
myarray[0]();
}

//Output
10
11
12
13
14

There is very easy way to resolve/avoid above scenario but we will take that up in future posts (hint: IIFE)

Identifier Resolution / Scope Chain

Having understood the variable object and scope its fairly easy to understand how the identifiers are resolved. Just remember

Scope chain  = [Current variable object] + [variable object of parent EC's]

Inside functions scope is represented by [[scope]]  property.When an identifier is encountered, the execution context’s scope chain is searched for an identifier with a matching name. The search begins at the first object in the scope chain, the function’s variable object, and continues towards the global object until the variable is found (or ends in an error if the variable is never found)


var outer = "outer";
function oh(){
var oh="oh";
my();

function my(){
var my="my";
God();

function God(){
var God ="God";
console.log(outer + ' ' + oh + ' ' + my + ' ' + God);
}
}
}

oh();

Scope of God = Variable object for God + Variable object for my +  variable object of oh + global Variable object.


Lets take another example

function setup(items){
var divs = document.getElementsByTagName('div');
var images = document.getElementsByTagName('images');
var button = document.getElementsByTagName('save-btn');

for(var i=0;i<items.length;i++){
process(items[i],divs[i]);
}

button.addEventListener('click',function(event){
console.log('saved');
},false);
}

Here [[scope]] of the function setup contains:
[0]: Variable object for setup, which  contains agruments &  items, variables divs, images, button & i along with this.
[1]: variable object for global object

Thus to resolve an identifier the engine will start from variable object and if not found move to Global object. 

Performance consideration: Using with and catch pushes another Variable object onto the top of scope chain stack and thus adds one more look up.

This concludes our introduction to variable (activation) objects and scope (chaining). Why introduction  one may ask, well to start the implication of these concepts is a learning process (for example Closures) and it does takes some time for these concepts to settle down.

Monday 11 August 2014

Execution Context - The fellowship begins

In one of the earlier post I talked about the type of variables in Javascript. Its time to build over that introduction and enlighten our self with the knowledge & power ( don't forget quirks) of the variables(types) in Javascript. Lets get started.

Obi Wan: Anakin what have you learned so for about variables in Javascript.

Anakin: Master  we know that variables in Javascript can have primitive or reference values. Primitive values are simple values Boolean, string, null, undefined, Numeric. When we work with primitive values we work with the actual value stored in the variable.Reference values are object that are made up of multiple values, they are essentially objects stored in memory.

Obi Wan: Good tell me more about the Reference values.

Anakin:Yes Master when we manipulate the object we are actually working on a reference of the object rather than the object itself.

To give you the crux of above discussion, in Javascript we have variables and these variables can have either a primitive value or a reference value. 

var a = "myname" // variable with primitive value
var b = new object(); // variable with reference value

One important point to remember is that we can add properties to reference variables (acting objects), however its not possible in primitive variables.

Thus continuing above example, this is perfectly valid:

b.name="Ninja"
console.log(b.name); //Ninja

However if we try to add a dynamic property to a variables with primitive value nothing will happen - really nothing happens.
var a = 5;
a.IsPrime = false
console.log(a.IsPrime); // undefined.

when a variable with primitive type is copied a new variable with same value, meaning there is no relation among the two variables

However this is different in variables with reference values, here the reference pointing to the value is  copied thus both the copies will point to the same object. Thus if any modification to the value will be reflected for both pointers.

Similarly when a variable with primitive value is passed as an argument to a function its actually the copy of outer variable which gets passed as the argument thus any modification made to the value in the function is local and does not effects the outer variables value.

Again for the variables with reference values the copy of the pointer is passed as the argument, thus any modifications made to the value inside the function will get reflected.

var val = new Object();
val.name="foo";
console.log(val.name); //foo
val = Param(val);
console.log(val.name); //foo++

function Param(value){
value.name="foo++"
return value;
}

Determining  type

Using typeof operator we can determine if a variable is of primitive type.
For null the typeof operator returns object

var n = null;
typeof  n; //object

for reference values typeof doesnt works it basically returns object for all reference variables. Thus for reference variables we use instanceof 

May the Scope be with you - Mystic Execution Context

In Javascript the concept of execution context is bit different than 4G language like C# or Java. Execution context of a function is like a property bag which defines what other data the function has access to, as well as how it should behave. This property bag is called variable object, upon this all of  the variables of the functions exists.

Except from Professional Javascript for Web Developers

Each function/variable has its own execution context thus starting from the browser window object a stack is created with each function call the first element is the window variable. When ever the code execution flows into a function, the execution context of the function is pushed to the stack, when the function execution is finished the execution context is popped out of stack.

Obi Wan: My dear Anakin I hope this clarifies what is Execution context (EC) ?
Anakin: Obi Wan this seems to be a dialect I haven't learned yet.

Obi Wan: You need to clear your minds young Anakin, may the force with you.

Think of EC aka Scope as the environment associated with the executing Javascript code. Given this EC can be either:
  1. Global Context - Higher most context in which the code executes by default. window in browser
  2. Function Context - Created with execution of each function call.
  3. Eval (This is first and last we mention of he who should not be named)
Thus we will always have a single global EC but we can have multiple function EC. Javascript interpreter is single thread (thank God for that) thus it can execute only one action/event at a time which means that the events/action get queued in something called Execution Stack.


Considering that the code execution is call to Function 1 followed by Function 2 &3.

Thus when the Javascript starts executing it encounters the global context and then all followed function calls will be added to the Execution stack (keep this in mind as this would help us in understanding how the identifiers are resolved)

Also if a function calls itself even then a new EC will be created and pushed to stack.

So in preparation of executing a function the EC is created and is augmented with:

  1. Create scope chain (will discuss the scope chain later in detail)
  2. Create argument
  3. Create this 
Once our EC is pumped up with these object (technically incorrect but should convey the idea) then execution of code happens under the environment provided by EC.

Thus to imagine this is how the EC would look like


Thus to summarize Execution Context is bundled of Variable object (in case of functions also known as Activation object), Scope chain and this.

In coming sections I will take up how the fellowship of Variable object (Man), Scope(Elfs) and this (Dwarfs) unite to help Frodo (developers) conquer the Ring (Javascript)  and try to elaborate how they effect :
Hoisting
Identifier resolution
context.

Stay tuned :)



Wednesday 6 August 2014

Equality operators in Javascript - My First googly

Among other concepts of Javascipt where I stumbled this one was a complete bouncer (can't blame a citizen of Cricket crazy country).

To grasp the concept of
Equal (==)
Not-Equal(!=)
Identically Equal(===)
Not Identically Equal(!==)

lets first talk about type coercion.

What ECMAScript ( Javascript) does is that it tries to align the type of operands before comparison , this is simply type coercion. This simple but powerful concept is cause of some good quirks in Javascript.

Equal & Not Equal

Equal and Not Equal performs the type coercion, meaning that before performing the comparison Javascript attempts to convert the type of operands to be same

Following rules are applied for conversion:
  • Boolean are converted to numeric
         false == 0 //true
         true ==1 //true
  • When comparing string with numeric, string is converted to numeric
         "1" == 1 //true
  • Comparing object with primitive, valueof is called on the object to get the primitive value of the object and that is used for comparison.
  • Value of null and undefined are equal. (yes null== undefined is true)
  • Value of null and undefined is not converted to anything else.
        null ==5// false
  • Special treatment is given to NaN. If one of the operands is NaN equality operator returns false and not equality returns true. 
  • NaN is not equal to NaN.
  • If both operands are object then if they are pointing to same object then only they are equal else not equal.
         var a = new Object();
         a.val =5;          var b = new Object();          b.val=5;          console.log(a==b); // false

         var a = new Object();
         a.val =5;          var b = a;          console.log(a==b); // true



Identically Equal and Not Identically Equal

No type coercion is involved in these thus not issues due to type conversion. Thus
       "1" === 1 // false
        null === undefined //true

Word of advice, if not sure and to maintain the consistency always use Identically Equal and Not Identically Equal.

Tuesday 5 August 2014

Values, Variables in Javascript - The Building Blocks

Data types - Fundamental building blocks of any language is the literals. 


Like C#, Javascript also boasts of value type and object but it goes without saying its not all same.

Value types: Fantastic Five
  1. Numbers: wrapper object to allow working with numeric values.
  2. Boolean: wrapper object over boolean values.
  3. Strings: wrapper over a sequence of characters.
  4. null:a special keyword denoting a null value. Note that Javascript is case sensitive thus null is not equal to NULL.
  5. undefined: as the name suggest if something is not defined then its undefined. Note that null is not same as undefined. To give an example
         var a;
          console.log(a); // undefined.
Apart from these primitive types JS has an object (yeah....) and functions (so what). But in JS an object is fundamentally just a collection of name/value pairs (duh isnt that a JSON object - well hold your horses we will come back later to that).

Hmm so what is a function, well if I have to put in possibly most simple terms functions are the objects which can be executed.

Playing with Data type:

JS is a dynamic typed language, what this means is that you don't have to specify the data type of a type when you declare it. Its the JS interpreter which automatically implies the data type for a variable during the script execution - real nice and cause of our very first confusion.

Since JS is dynamically typed language  thus following statement are valid

var name ="myname";
name = 5;

So if we use + operator with numeric operand it results in a numeric value, however it we use + operator with a numeric and string then JS converts numeric to string.

This paradigm is not followed for other operators for example 

"55"-5 // 50
"55"+5 // 555 -> converting numeric to string

Variables

Declaring variables: We can declare variable in JS in two ways:
  1. Using Var keyword and then assigning the value. This can be used to create local as well as global variables
  2. Without using Var keyword and directly assigning the value. This always creates a global variable
Always declare variables using var keyword (period)

A variable declared using var keyword with no initial value specified has the default value of undefined. Attempt to access an undeclared variable with raise ReferenceError exception.

A variable declared inside a function without var is indeed a global variable.

function foo(){
 name='foo'; //global scope
var age=30; //local scope
}

typeof Operator


Using typeof operator on primitive type returns one of the following:
  1. undefined if the  value is undefined
  2. boolean if value is boolean
  3. string if value is string
  4. number if value is number
  5. object if value is an object (i.e not a function)
  6. function if value is function
Hey but the fantastic five also had null, what about that?
Well calling typeof on null returns object, to think about it null is actually an empty object.

The object type

In JS an object is a collection of name value pair. A new instance of object can be created using new keyword.
var o = new object();  // look its all same as done in C# or Java

This is good for now we will uncover object in detail in coming sections




Monday 4 August 2014

Exploring Javascript - The First step

Exploring Javascript

Having worked in C# and WCF on a typical server side programming, my heart often wandered what is happening in the world of front end. I was fascinated with smart device programming for Android and iPhone using the native language but at the same time i was interested in HTML5 and Javascript. 

This led me to explore certain aspects of Javascript, I often used to wonder that how hard could it be to learn a scripting language which was written in just about 15 days! but boy was I wrong :)

And then came the fateful day when I got the chance to work on a JS project, but I had to prove that I am up for the task.

So I started fooling around with Javascript using few resources on net and few good books.

Initially i started with the mindset of learning Javascript by relating the concepts with a fourth generation language like C#, however soon i realized that its a different monster and i can only hope to get the concepts right if I start with a clean slate.

Having said that you may find me comparing Javascript with C# at times but as they say "Old habbits are hard to die"

What I present here is my journey from a C# .net developer to taking dive in the world of Javascript.

ECMA Script - A brief Introduction

In all the forthcoming post I will focus on Javascript, however I should give a moment and mention ECMA Script.

Now I am not going to go on the details of the specification number(s) and the guidelines however I must mention a brief about the relation among Javascript and ECMA Script.

It was Netscape who pioneered  Javascript (initially Livescript) and Microsoft then came up with its own version of a scripting language Jscript.

But there was no standard as such, thus enters the European Computer Manufacturer Association (ECMA) which takes up the task of specifying a standardize programming language based on Javascript.

This standardized version of Javascript is called ECMAscript.

So what is the relation between Javascript and ECMAscript, if you ask me ECMA script is like a standard guidelines ( a blueprint) and Javascript is its implementation, other implementation being Jscript.

That's all for this post, I am not sure about the destination but for sure going to enjoy the journey I have started.