Featured post

Closures, Lexical Scoping And Scope chain In JavaScript

Closures...You have heard a lot, or might have tried to study from different sources, but failed to get the point. Well to under...

Thursday, 11 February 2016

Event Handling in JavaScript (Part 1)


In this post I will cover some basic fundamentals of Event Handling and what are the different techniques of registering events.

Client side JavaScript program use an asynchronous event-driven programming model. If anything interesting happens to a document or window or element, browser generates an event for it. That event gets registered in event loop. Browser then fires event handler function for topmost event from event loop.

Lets understand above process in simple words. Event is something which is fired when user interacts with browser. Event can be click on button, hover on link, scroll on window, load of document, etc. If you want to perform any particular task on any event then you can write a function for that event. That function will be termed as Event Handler or Event Listener for that event.
If you fire lot of events back to back then browser will register all those event in a queue and will execute their event handler function one by one. That queue is called as Event Loop. Since JavaScript does not support multi tasking, those event handler functions will execute one after another.
Event Type is a string that specifies what kind of event occurred. Type "mousemove" signifies movement of mouse, "keydown" means key on the keyboard is pressed down and etc. Event Type sometimes called as Event Name.
Event Target is an object on which event has occurred or with which event is associated. Load event on Window, load event on document, click event on button etc. Some common event targets are Window, document or html element objects.
Event Object is an object that is associated with particular event and contains details about the event. Event Objects are passed as an argument to the event handler function. All event Objects have a type and target property. Type property specifies the event type and target property specifies Event target. (In IE8 or before use srcElement instead of target).
Event Propagation is process in which browser identifies objects on which event handler function should be triggered upon. Event Propagation is mostly confused as synonym of Event Bubbling but Event Propagation is much wider concept.
Event Propagation also includes the concept of Event Capturing which is opposite to Event Bubbling.


Event Bubbling and Event Capturing:
Suppose click event has occurred on anchor tag, browser will execute handler for that event. Now event will bubble up to the enclosing element of anchor tag maybe <p> tag, now handler for <p> tag will be executed. Again event will bubble up to the enclosing element of <p> tag, that could be <div> tag. Handler for <div> tag will now get executed. This process is event bubbling.
Event Capturing is opposite process of event bubbling. First handler for highest hierarchy element will get executed, then bubbles down to child element and this process goes on until it reaches to the parent of the element on which event has occurred initially. Interesting part is handler function of element on which originally event has occurred will not get executed.
Event capturing provides an opportunity to peek at events before they are delivered to their targets. A capturing event handler can be used for debugging.

Registering Event Handlers


You can register JavaScript Event Handlers in two different ways, set a property on the object or document element that is the event target or pass the handler to a method of the object or element. There are two versions of each technique.

 

Setting Event Handler Properties:

Easiest way to register an event handler function is by setting the Event name property of Event target to the desired event handler function.

Event target properties have name that consists of "on" prefix like, onmouseover, onclick, onhover etc. Event targets as earlier mentioned can be window, document etc.

window.onload = function() {
   
      // Look up an div tag with id header
      var header = document.getElementById("header");
      console.log(header);      // Printing element
}

This technique works for all kinds of browsers but it has some shortcomings. It won't allow you to register more than one type of event handler function for any event on particular event target. Means?? You can register only one event handler function for onload event on window object. If you are writing a library just go for addEventListener() method (Will explain this technique later in the post).

 

Setting Event Handler Attributes:

Another popular way of registering event is by setting attribute on corresponding HTML tag. Like:

<button type="submit" id="ironman" onclick="alert(I am IronMan!);">Identify</button>
<button type="submit" id="spiderman" onclick="greatPower()">Famous Dialog</button>
<script>
      var greatPower = function() {
            alert("Power is directly proportional to Responsibility. :p");
      }
</script>

There are lot of things to remember in order to use this technique.
  • Attribute value should always be JavaScript String
  • If there are multiple statements in attribute value then separate them with semicolon ;
  • Last thing to remember, you are mixing JavaScript code with HTML content. Some programmers avoid this technique in order to keep their code clean

 

addEventListener():

Here comes the technique which I will suggest you to use. This technique is supported by all the browsers other than IE8 and below. All Objects like window, document and other document elements has addEventListener method defined. This method takes three parameters, first: event name (prefix "on" is not used in the name of the event), second: event handler function, third: a Boolean value determining whether the event registered as an capturing event or not. You are wondering about the third parameter. Right? If passed true, event will registered as an capturing event else not. Basically capturing handlers of the window object are invoked first, then the capturing handlers of the document object, then the body object, and so on down the DOM tree until the capturing event handlers of the parent of the event target are invoked. Capturing event handlers registered on the event target itself are not invoked.

<button id="myButton" type="submit" value="submit">Submit</button>
<script>
      var b = document.getElementById("myButton");

       var clickHandler = function() {
             alert("Please do not block ads on this blog.");
      }
 
      b.addEventListener("click", clickHandler, false);

</script>

addEventListener() is paired with removeEventListener() method that expects the same three arguments but removes the event handler function from the object rather than adding it.

 

attachEvent():

Internet prior to IE9 does not support addEventListener() or removeEventListener(). Instead it uses attachEvent() or detachEvent() methods. There are some minor differences between these two method's implementation. 

Internet Explorer does not support Event Capturing, therefore there is no third parameter required in attachEvent() and detachEvent().
Unlike addEventListener(), attachEvent() takes prefix "on" in event name.
attachEvent() allows same event handler function to be registered more than once, allowing registered function to be invoked as many times as it was registered.

<button id="myButton" type="submit" value="submit">Submit</button>
<script>
      var b = document.getElementById("myButton");

       var clickHandler = function() {
             alert("Please do not block ads on this blog.");
      }

       if(window.addEventListener) {
              b.addEventListener("click", clickHandler, false);
        } else if(window.attachEvent) {
               b.attachEvent("onclick", clickHandler);
       }
</script>

Above code will ensure that if browser supports addEventListener() than it will use that method only else it will go attachEvent method. This practice makes your application backward browser compatible.

In next post we will explore the Event Handler Invocation process..

Monday, 8 February 2016

Difference between Context and Scope in JavaScript


Context and Scope both are completely different things which commonly being misunderstood as same by many people.
Context is this of the currently executing function, i.e. the environment in which function is getting executed. Scope on the other hand refers to the variables and methods which is accessible by currently executing function.

Value of this associated with any function gets dynamically assigned depending on how function is getting invoked.

To understand the context/this properly we need to first understand how functions get invoked.

JavaScript functions can be invoked in four different ways:
  • as functions
  • as methods
  • as constructors
  • indirectly through their call() and apply() methods

Function Invocation


This is typical and most obvious way to invoke a function. Function name and parameters inside the round brackets. These parameters will get assigned to the parameters defined in function definition.

Function definition:


var a = function (parameter_1, parameter_2) {
      console.log(parameter_1);
      console.log(parameter_2);
}      // Function Definition
var param_1 = "This is Parameter 1";
var param_2 = "This is Parameter 2";
a(param_1, param_2);      // Function invocation

Here a() function is getting invoked by window object. so this for a() function would be window Object.

var a = function (parameter_1, parameter_2) {
      console.log(this);
}      // Function Definition
var param_1 = "This is Parameter 1";
var param_2 = "This is Parameter 2";
a(param_1, param_2);       // Print Window Object
Above code will print Window Object on console.

Method Invocation


If function a() is associated with any object or if function a() is property of any object then that function a() will be called method.

var o = {
      f: function() {
            console.log("I am method of object o.");
      }
}
o.f();      // Method Invocation

Here f() function is getting invoked by object o. So this associated with function would be object o.

var o = {
      f: function() {
            console.log(this);
      }
}
o.f();       // Print o object

Constructor Invocation


If a function is getting invoked by new keyword than it is constructor invocation. Constructors are supposed to initialize the object and return the newly created object. this associated with constructor function, is prototype object which will initialize new object and finally return it.

var a = function(p) {
      this.p1 = p;
      console.log(this);      //  Print prototype object
}
var obj = new a("Bazinga!!");
obj.p1;      //  Says Bazinga!!

While creating constructors you are not supposed to return anything, However if you explicitly return any object from constructor than your object will get returned instead of newly created object.
If you return any primitive value or return nothing than return statement will get ignored and newly created object will be returned.

Indirect Invocation


If you explicitly want to define the context/this of function than use either call() or apply() method of window object.
var o = {
      f: function() {
            console.log("I am method of object o.");
      }
      f();      // this of function f() will be window object.
}
o.f();      // this of function f() will be object o.
var newObject = {};
f.call(newObject);      // this of function f() will be object newObject.
f.apply(newObject);      // this of function f() will be object newObject.
Both methods allow you to specify the arguments for the invocation. The call() method uses its own argument list as arguments to the function f() and the apply method expects an array of values to be used as arguments for function f().

Wednesday, 3 February 2016

Closures, Lexical Scoping And Scope chain In JavaScript

Closures...You have heard a lot, or might have tried to study from different sources, but failed to get the point.

Well to understand the closure we must have to take deep dive into the basic behavior of JavaScript.

First lets see what is Lexical Scoping.

Like Python, JavaScript also supports Lexical Scoping..means inner functions are able to access the scope (variable/methods) of outer function where it has been defined and not be able to access the scope where it is being called.

Lets understand this with an example:

var a = function () {
      var foo = "Print me";
      var b = function () {
            console.log(foo);
      }
      return b;
}
var catchReturn = a();
catchReturn();      // Says Print me

Lets understand above code line by line.

This is outer function:
var a = function () {
   
}

Variable foo defined inside the outer function a (foo is local variable of outer function a):
var a = function () {
      var foo = "Print me";
}

Inner function b having access of all the variables and methods defined in outer function a:
var b = function () {
      console,log(foo);
}
Since inner function has access of outer function's scope, it will be able to print foo variable inside it.

calling a function and storing result in catchReturn variable.
var catchReturn = a();
Since a function is returning an inner function, catchReturn will be storing inner function.

Calling inner function through catchReturn
catchReturn();
This will execute inner function. Since inner function has access to the scope of outer function it will be able to print foo variable.

Now lets take it to another level.

var foo = "Will it get printed???? ^_~"
var a = function () {
      var foo = "Miracle Happens!!";
      var b = function () {
            console.log(foo);
      }
      return b;
}
var catchReturn = a();
catchReturn();      // what do you think it will print?

Kudos if you say Miracle Happens!!. Others ask why?? Lets see why.

Well because of scope chain or scope hierarchy. Inner function b has access to global variable foo and also local variable foo of parent function. Since catchReturn is getting executed in global context it should print "Will it get printed???? ^_~" (according to the rules of dynamic scoping) but since JavaScript supports Lexical Scoping, it will look into the scope chain of the location where b function is defined i.e inside a (outer function)

Now that we have got good understanding of Lexical Scoping, we can move towards Closures.

Closure is an inner functions that has access to the outer function's variables/scope chain. That means all the inner functions are closures. But what is the point of closure. Can't we directly access outer function's variable through outer function only. Well in some scenarios, NO. Lets take an example.

var i;
for( i = 1; i<= 5; i++ ) {
      setTimeout(function() { console.log(i) }, 1000);
}

what will get printed? BIG NO to those who say 1 2 3 4 5. Actual answer will be 6 6 6 6 6. Why you ask. setTimeout will execute after 1000 mSec. Till then for loop will get iterated completely atlast setting the value of i to 6. Now all the setTimeout functions will get executed printing the value of i which is 6 because of lexical scoping.

What if I want to print 1 2 3 4 5. Here comes Closures in the picture.

var i;
for( i = 1; i<= 5; i++ ) {
      (function(stored_separate_i) {
            setTimeout(function() { console.log(stored_separate_i) }, 1000);
      })(i);
}

This will print the desired output i.e. 1 2 3 4 5.

On each iteration of for loop there is separate individual self executing function in which we are passing i. This separate self executing function will get executed each time storing the value of i in a variable stored_separate_i. Now function inside the setTimeout has seperate value of i in stored_separate_i which will get printed. Here closure is the inner function which is defined in setTimeout and outer function will be self executing function defined inside the for loop.

Make sure to bookmark this post as you will need to revise the concept of closures,

Tuesday, 2 February 2016

Reasons Why JavaScript Is Weird


{ Fun Facts of JavaScript }

Earlier back in 90's, pages displayed on browser has to be static and designed with basic HTML and CSS. Java Applets were complete failure at client side, then came JavaScript that was created in 10 days. Looking at its tremendous performance on client side it was adopted in early stages as client side scripting language and not given a chance to get mature. This is the reason why JavaScript has lot of bugs. This post contains some major issues in the language and reason behind those design decisions.

NaN === NaN // Returns False
undefined === undefined // Says True
What is wrong with NaN?
Actually JavaScript or say ECMAScript follows IEEE-754 standard which purely says NaNs should never be equal.
NaN is designed to bubble up all the calculations flaws buried deep down in your complex code. If NaN is kept with any operator then it will break the calculation by indicating meaningful results. Otherwise by identity NaN/NaN should equal 1, (NaN/NaN)==1, (NaN*1)==NaN, etc which surely we do not want.

Functions can be nested

Well, if you compare JavaScript with more strictly typed languages like Java or C# then you will find lot of new things to deal with or to remember. So first thing first, stop comparing any Loosely typed language with Strongly typed Language. Now open your mind for some new, amazing features of Loosely typed Language.
var AnikenFeatures = function () {
        var LukeFeatures = function() {
    return “Force!!”
}
return “Dark side of Force!!”
}
Functions are another type of variable in JavaScript. When we create a function within another function then it changes the scope of the function in same way as it changes the scope of variable. Main advantage: Closures, which results in reducing total global namespace pollution.

Functions can execute themselves

(function() { console.log('Valar Morghulis'); })(); // Says Valar Morghulis
This anonymous function will execute itself without need of any object or context. So if we are not giving context and it is automatically getting executed then what would be the default this of the executed function. Let’s check:
(function() {
        console.log(this); // Says Window Object
})();
Above code will return Window object, i.e. default context/this of each executed function will be Window Object.
But what is the purpose of self executing function. It’s nothing but for variable scoping. Variables declared and defined within self executing function can only be accessed or available in that function. Developer need not have to worry about the variables named in other JavaScript code block.
Main benefit lies when your application contains lot of external JavaScript libraries. There is fair chance of getting same name for more than one function or variable. In that case, library loaded later will override the definition of function/variable of previous library.
Complete code of JQuery library is wrapped inside the self executing function because of the above mentioned reasons.

Defining Undefined

var a;
if(a === undefined){
    console.log(“This is undefined”)
} // Says This is undefined
Default value of each variable if not defined is - undefined. This can be used as trick in many situations. But mainly to check if an object/variable contains any method/value.
JQuery Code:
(function(Global) {
    Global.foo = {};
})(typeof window !== “undefined” ? window : this)
Here, in this self executing function, parameter is passed by checking weather window object is available or not. If not then this will be transferred in place of window object. Well in that case value of this would be the object which is invoking the function.

Typeof null === Object
console.log(typeof null === object) // It says true!!
Why in the name of god it returns true. Because Null in JavaScript is Object. You ask why? Here is fun fact:
This is a bug and one that unfortunately can’t be fixed, because it would break existing code. Let’s explore the history of this bug.
This bug exists from the first version of JavaScript where values were represented as a type tag and a value, with the type tag for objects being 0, and null was represented as the NULL pointer (0x00 on most platforms). As a result, null had 0 as a type tag, hence the bogus typeof return value.
A "fix" was proposed for ECMAScript (via an opt-in). It would have resulted in:
typeof null === 'null'
... but this change was rejected, due to issues with code using this specific "quirk" to test for null.

0.2 + 0.1 == 0.3 // Returns False

Whaattt!!!!!!!!
Because internally, computers use a format (binary floating-point) that cannot accurately represent a number like 0.1, 0.2 or 0.3 at all.
When the code is compiled or interpreted, your “0.1” is already rounded to the nearest number in that format, which results in a small rounding error even before the calculation happens.
You ask why do computers use such a stupid system?
It’s not stupid, just different. Decimal numbers cannot accurately represent a number like 1/3, so you have to round to something like 0.33 - and you don’t expect 0.33 + 0.33 + 0.33 to add up to 1, either - do you?
Computers use binary numbers because they’re faster at dealing with those, and because for most calculations, a tiny error in the 17th decimal place doesn’t matter at all since the numbers you work with aren’t round (or that precise) anyway.