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

Monday 29 February 2016

Fundamentals of CSS - Floating, Positioning and Box model

You must be wondering why in the name of god I chose this topic to write on. Well, recently I came across few interesting concepts and thought every Front End Developer should know at least some fundamentals of CSS. Front End Developers mostly focuses on JavaScript and others have at least started considering about learning JavaScript (because of hot, new frameworks or libraries like AngularJS and ReactJS). But every single developer takes CSS and HTML for granted. I am here just trying to familiarize everyone of you with basics of CSS :).

Three of most important concepts to grasp are floating, positioning and box model. These 3 things can control whole layout of your page.

But first lets understand what is Block Level and Inline Level element.

An element can be of two types: Block level element and Inline level element. Block level elements (div, p) takes space of whole block in a page and align themselves vertically one after another. Whereas inline elements (a, span, strong) takes up inline space and lays themselves horizontally next to each other.



You can change behaviour/behavior of inline element as block by setting its display property to block and you can also make any block level element disappear from page by setting its display property to none. In this case element will not be visible and it won't even take any space on the web page.
We can set all the four (top, bottom, left, right) margins ,paddings and border of block level element but can only set two (left and right) margins and paddings of inline elements. That is only horizontal spacing can be set on inline elements. Vertical spacing do not affect inline elements. Then what is workaround? Set display property of inline element as inline-block. As name indicates the element will behave as inline element i.e. they will align themselves horizontally next to each other. Plus, you will be able to set vertical margins and paddings of that element. Another workaround is to set line-height property of inline element. If value of line-height is greater than height of inline element then extra space will get adjusted above and below the content equally and content will automatically get adjusted in center vertically.
All the inline elements are contained in Line Box. Line Box may contain multiple inline elements. Height of line box would be same as the highest inline element. If elements inside the line box can not adjust themselves in one line than they will be passed in next vertical line into another Line Box.

Line Box containing multiple inline elements

Split Line Box

Box model


CSS3 has introduced Box model which specifies how elements are displayed on browser. Every element is considered as an rectangular box consist of element, padding, margin and border. Padding is applied around the element, after padding border is applied around padding. Border could be solid, dashed or dotted. And finally after border, margin is applied.


Older versions of Internet Explorer have some different understanding of Box Model. According to CSS3 standards width and height of element only consider width and height of content whereas IE consider height and width of content + padding + borders. Technically, IE version of box model is correct. Consider a box of stuff, more and more we add paddings/stuffing inside the box, less space will be left for content.


What if I want to use this philosophy of box model in other browsers? Well, we got a property box-sizing to deal with this requirement. box-sizing can be set to content-box or border-box. box-sizing: content-box will consider actual width and height to width and height of content only. Whereas, box-sizing: border-box will consider actual width and height to width and height of content + padding + border.

Margin Collapsing

Margin Collapsing is another interesting concept. While laying out page, when two or more vertical margins meet, they collapse with each other resulting in collapsed margin's height as larger among the two collapsing margin.


This concept may seem weird at first but if you give deep thoughts than you will see why it actually results in good layout.

Above image gives good example of margin collapsing. It would have looked weird if space between Data1 and Data2 were double.

Positioning


In spite of reading position property from different sources you fail to remember the meaning of each value. Right? Lets give this post a shot. I hope you need not have to read it again.


position: relative

Element with property position: relative will not affect anything (neither the flow of all other elements nor position of element itself) unless you set the left, right, top or bottom property of element. This type of positioning is considered as part of normal-flow positioning. If you set left: 20px; then position of element will be shifted to 20px to left from its actual position. That is position relative is relative to its actual position.



position: absolute

Element with position absolute behaves somewhat different than relative. In relative, position of element remain in normal flow and then shifted according to left, right, top and bottom values but in absolute positioning, element is not part of the normal flow. Other elements do not consider absolute positioned elements as there siblings. Absolute positioned elements are not given any space in the document. These elements are relative to there immediate parent element. Left, right, top and bottom properties are relative to their parent.



position: fixed

Position fixed is a type of absolute positioning. Absolute position is relative to its immediate parent whereas fixed positioning is relative to the view port. It does not matter where the scroll is moving the window, but fixed positioned element will always remain stick to its position on view port. Left, right, top and bottom properties will be relative to the view port.
You have seen some sticky ads on websites which will not move even if you scroll. Those are example of fixed positioning.


Z-index

Above positioning of element might result in overlapping of multiple elements, then how to prioritize which element should remain on top and which should be on bottom? Property named z-index will come in picture. Element having greatest z-index value will remain on top and element with smallest z-index value will remain on bottom. There is no limitations for z-index value in the CSS Standard but most browsers limit it to signed 32-bit values in practice. There can be negative value of z-index too.

Floating


Floated box can be shifted either to left or right until its outer edge touches padding of containing box or margin of another floated box. Floated box are not considered in normal flow so other elements behaves as if floated box never existed and do not leave any space for floated boxes. This may result in overlapping of floated boxes over non floated boxes.


In below diagram, initially all the boxes are vertically blow each other. After floating box 1 to right, box 2 and 3 consider that box 1 does not exist in normal flow and they moves up.


In below diagram initially box 1 is floated left, and overlaps box 2. Then all the boxes are floated to left behaves differently in different scenarios.  


To stop boxes flowing around, you need to apply a clear property to the element next to it. clear property can be left, right, both, or none and it indicates which side of box should not be next to a floated box.

Earlier before media queries, floated box were used to create responsive designs.

Wednesday 24 February 2016

Event Handling in JavaScript (Part 2)


We have already covered some basics of Event Handling in Part 1. We have seen how we can register events on objects like window, document or any document elements objects. Before moving further I will recommend you to read that first. This time we will explore Event Handler Invocation process.

Event Handler Invocation:


Once you have registered event handlers, web browser will automatically invoke it when event of specified type occur on specified object. In this section we will cover arguments on event handler, event handler context, event handler scope, return value of event handler, invocation order and last but not the least event propagation and cancellation. This will surely give you better understanding on Event Handling.

Event Handler Argument

Event Handlers are mostly invoked with an event object as their argument. By mostly I mean IE8 and below versions of IE (as usual :/ ) do not pass any object in argument. Instead event object is available through the global variable window.event.
For compatibility we can write our handler function as:

var handler = function(event) {
      event = event || window.event;
}

This || says that if event is undefined (i.e. not passed as argument) then refer to the window.event variable.
The property of the event object provide details about the event. The type property of event object specifies the type of the event that has occured.

Event Handler Context

As we know there are 4 different ways in which function can be invoked. All those ways differ in setting the context/this of the function. Before moving further I recommend you to read this post first for more information on context/this.
By now, I hope you know method invocation and function invocation. We will need that knowledge to understand event handler context.

When you register your event handler by setting a property of element like this:
e.onlick = function() {.....};
then event handlers are invoked as method invocation since element is an object and we are defining property of an object. In this case our context/this refers to the event target on which handler is registered and invoked.

e.onclick = function() {
      console.log(this);      // It will display element on which click event is fired.
}

Even when handler is registered using addEventListener() then also the context/this will be set to event target i.e. element on which event is fired or registered. Unfortunately, it is not true with attachEvent() method. Handlers regisered through with attachEvent() are invoked as functions and sets this/context to global (Window) object. But we can have workaround for this.

function addEvent(target, type, handler) {
      if (target.addEventListener) {
            target.addEventListener(type, handler, false)
      } else {
            target.attachEvent("on" + type, function(event) {
                  return handler.call(target, event);
            });
      }
}
But event handler using this method can nto be removed because second parameter (handler function for attachEvent()) is ananymous and is not retained anywhere to be passed in detachEvent().

Event Handler Scope

We have seen that JavaScript, like Python, is lexically scoped means function able to access the scope chain where it has been defined and not where it has been called. For more clear understanding on scope in JavaScript, follow this post.
So like all the other JavaScript functions, event handlers are also lexically scoped. They are executed in the scope in which they are defined and not the scope from which they are invoked.

However there will always be an weird case since we are talking about JavaScript. Event Handlers which are registered as HTML attributes have access to global variables but not to any local variables. But, for some reasons, they have access to modified scope chain. Event Handlers defined by HTML element have access to element's attribute, the containing form object and the document object as well, as if they are local variables to the handler function.

Handler Return Value

Somethimes, when return value of handler function is set to false then browser does not perform the default action. Means??? Suppose you have submitted a form whose handler is registerd via setting HTML attribute or by setting an object property, and if handler returns false then form will not get submitted. You can write client side validation in handler function.
Another use of returning false could be in onkeypress event's handler function. Check if pressed key is valid or not and return false if not valid (can be used when validation input email or etc.).

But one important point here to notice is, return value false will only work if handler is registered by setting HTML attribute or by object property. It won't work if handlers are registered through addEventListener() or attachEvent() methods. To prevent default actions from handler function registered through these two methods, you must have to call the preventDefault() method or set the returnValue property of the event object. (preventDefault() for addEventListener() and returnValue = false for attachEvent()).

Invocation Order

There might be more than one event handler functon registered on single HTML element or object. When an appropriate event occurs, browser must have to prioritize between the event handler funciton's execution sequence. Browser follows following order to execute a handler funciton in sequence:
  • Handlers registered by setting an object property or HTML attribute will be invoked first.
  • Handlers registered with addEventListener() will be invoked in order they were registered.
  • Handlers registered with attachEvent() can be invoked in any order and you should not be dependent on sequence of this order.

Event Propagation

Whenever an event occurs on Window object, browser executes the handler function of respective event. But for other event targets like document object or any other html element, story is little different. After executing Event Handler function, event bubbles up to the document hierarchy level. Now handler function of upper level element will execute, and this goes on until it reaches to Window Object. (Exception Events which do not bubble up: focus, blur and scroll events.) This Event Bubbling is actually third phase of Event Propagation process. Executing Event Handler function is itself actually second phase. You ask what is first phase? Remember the third Boolean parameter on addEventListener() function? Well, if passed true in that parameter, event handler is registered as an capturing event handler. What difference does capturing event handler function makes? If function registered as capturing Event Handler, the top most hierarchy function will execute first (i.e., handler of Window Object),then its child and this goes on until immediate parent of event target on which event has actually occurred. And main point is it will never execute handler function of event target on which event has actually occurred. (Basically event event Capturing is opposite process of Event Bubbling). Event Capturing is mostly used for debugging purposes.

Event Cancellation

To cancel event propagation, use stopPropagation() method on handlers registered through addEventListener(). IE9 or before does not support stopPropagation(), instead, the IE event object has a property cancelBubble. Set this property to true to prevent any further propagation. There is another method named stopImmediatePropagation(). Like stopPropagation(), this method prevents the propagation of events to any other objects. But it also prevents the invocation of any other event handlers registered on the same object.

Drop comments for any doubts.

Wednesday 17 February 2016

Object Oriented JavaScript - Objects, Classes, Constructors, Prototype and Inheritance

First lets understand what is Object Oriented programming and then we will relate it to JavaScript.

Mozilla Foundation has given a generalized definition of OOP.
Object Oriented Programming is a programming paradigm that uses abstraction to create models based on the real world.
Object Oriented Programming uses self contained pieces of code to develop applications. We call those pieces Objects. Objects are building blocks of our application. In OOP each object can receive messages, process data and send messages to other objects. Objects allows to create modularize applications. In some strongly typed languages like Java, C++, Objects refers to the instances of classes but unlike these languages, in JavaScript functions accomplishes the behavior of any class and then uses it.

Some basic terminologies of OOP with which you should be aware of:

Namespace:
A container, to bundle all application logic under one unique name.

Class:
Defines object's behavior. React as template for object's properties and methods.

Object:
Instance of class.

Property:
Object's characteristic

Method:
Object's capability or subroutine.

Constructor:
Method called during object creation in order to initialize the object.

Inheritance:
Class inheriting properties of another class.

Encapsulation:
Process of bundling data and methods that use the data.

Polymorphism:
Multiple forms of same methods and properties.

JavaScript does not implement all the the above terms typically as other strictly typed languages does, but JavaScript has its own way of supporting OOP. For example some browsers do not support class implementation (as we can not define class according to ECMA Script 5 standards), but JavaScript defines a function which typically behaves as class.

JavaScript supports Prototype based programming that doesn't uses class, but rather it first accomplishes the behavior of any class and then reuses it by decorating existing prototype objects.

Classes and Prototype:


In JavaScript, classes are collection of objects which has same prototype object. Every function in JavaScript has inbuilt prototype property. All the objects inheriting from that function actually inherits from that prototype property. Function works as an Class for the objects which actually shares methods defined in prototype property.

Before creating any class, first lets understand how can we inherit an object into another or lets take a deep dive into JavaScript Objects.

JavaScript Objects:


There are multiple ways to create an object in JavaScript defined in different versions of ECMAScript. First, basic way to define an object is through Object Literals.

var o = {};      // object o
var obj = {
      x: "I am String",      // String
      y: 2      // Number
}      // object obj

Objects defined/created using above method inherits properties/methods from the Parent of all the Objects or say Base object of all the objects called "Object". (I know there are lot of objects in this sentence :/ )
In simple terms we can say, JavaScript has provided us with an predefined object which has some inbuilt methods and properties and which acts as an parent of all the objects. That predefined object has name Object. Some basic methods defined in this object are hasOwnProperty, length, toString, valueOf and etc.. We will explore some methods shortly.

Till now we know that each JavaScript object or function has inbuilt property "prototype" and value of prototype is an object from which it inherits properties.

That means, prototype property of object o (from above example) is an object from which it inherits. We have already seen that o inherits from Object. So,

Object.getPrototypeOf(o)      // This will obviously display Object object (Predefined object of JavaScript)

Now what if I override prototype property or set it to null? Well, this is bad idea, I mean very bad idea. You can always override this property but if you do so, you will loose all the inbuilt/basic methods that you are getting from Object object. And who wants that..No one.

Object.getPrototypeOf(o)      // Will display Object object
o.__proto__ = null;
Object.getPrototypeOf(o)      // Null
o.toString();      // Will display TypeError: function not defined.

Lets check out second way to create an object in JavaScript using Object.create() method. This method was introduced in ECMAScript 5.

var obj = Object.create();

This will create an object similar to the object o. Here obj will also inherit from the Object object. So why in the name of god we need to different ways.
There is an difference between these two. Using Object.create(), we can explicitly define from which particular object we want to inherit by passing that object as first parameter.

var parent = {
       a: "this is parent"
}
var child = Object.create(parent);

Now child object is inheriting from the parent object. That is prototype of child is set to parent. So what about all the predefined methods of Object object. Well prototype of parent object is Object object. With this prototype chain child object will be able to access Object object's predefined methods and properties.
What if we want to define as well as declare the properties of the new object at the same time using Object.create(). We can achieve that by passing the second optional parameter.

var child = Object.create({a: "parent property"}, {
      foo: { writable: true, configurable: true, value: "Everything is weird." }
});

child object have property foo whose value is "Everything is weird". (We will discuss writable and configurable property later.). Also child object inherits from the object passed in first parameter.

Object.create() was introduced in ECMAScript 5. So before ES5, there might be some another way to create an object with desired prototype. Lets define an inherit method which inherits from an object passed in as parameter.

function inherit(p) {
      if (p == null) {
            throw TypeError();
      }
      if (Object.create)
            return Object.create(p);
      }
      if (typeof p !== "object" && typeof p !== "function") {
            throw TypeError();
      }
      function f(){};
      f.prototype = p;
      return new f();
}
var parent = {a: "I am parenting"};
var child = inherit(parent);

Lets understand inherit function line by line.

if (p == null) {
      throw TypeError();
}
If parameter passed is null then Exception will be thrown.

 if (Object.create)
      return Object.create(p);
}
If Object.create() is already defined than use it to create object and return it.

if (typeof p !== "object" && typeof p !== "function") {
      throw TypeError();
}
If parameter provided is neither an object nor function than also throw a TypeError. But if are using this condition than why do we need first condition for checking null value? That's because typeof null equals an object which is obviously weird (you can explore this more on my other post Reasons Why JavaScript is weird).

function f(){};
f.prototype = p;
return new f();
Here function f is an empty function which we will use as an constructor. We know that each function and object has inbuilt prototype property. One interesting fact about prototype property of constructor is that, all the objects created through constructor will inherit from the prototype property of that constructor.
Taking advantage of this fact we are setting prototype of constructor to the p (parent we have passed as parameter to inherit function). Now with new f(), we will be able to create an object and will return it.

We were able to pass the second parameter to Object.create() method in order to initialize the newly created object but with inherit method we can not do that.

Now that we have good understanding of Objects and prototype, we can jump to the Classes and Inheritance or say third way of creating an object.

As we already know that Class is just an collection of objects which inherits from same prototype object, we can create class by creating an prototype from which objects can inherit. In order to do that we can use our inherit() function defined above.

var c = function(initial, end) {
      var f = inherit(c.methods);
      f.initial = initial;
      f.end = end;
      return f;
}
c.methods = {
      sharedMethod: function() {
            console.log("I will be shared among all the objects.");
            console.log(this.initial + " " + this.end + " initial and end parameters are not shared among all objects. ")
      }
}
var obj = c(1, 9);
obj.sharedMethod();

Lets understand above code line by line.

var c = function(initial, end) {
}
Here c function can be considered as an class. This class takes 2 parameters initial and end.

var c = function(initial, end) {
      var f = inherit(c.methods);
}
Here Class c is using inherit method to set c.methods as an prototype of f object.

var c = function(initial, end) {
      var f = inherit(c.methods);
      f.initial = initial;
      f.end = end;
}
After creating an object f whose prototype is c.methods, we are setting variables of f object. This variables will not be shared among all the objects.

c.methods = {
      sharedMethod: function() {
            console.log("I will be shared among all the objects.");
            console.log(this.initial + " " + this.end + " initial and end parameters are not shared among all objects. ")
      }
}
Here c.methods will act as an prototype object which is getting inherited by all the objects of class c. Methods defined inside c.methods will be shared among all the objects of class c.

Classes and Constructors:


We have explored way to create Classes using prototype. Now we will create a class using constructors. Constructors can be defined as public face of Class as classof() property for an object returns the constructor name from which that object is created. But constructors should never be confused with class. Above method to create an class can be modified using constructors.

var C = function(initial, end) {
      this.initial = initial;
      this.end = end;
}
C.prototype = {
      sharedMethod: function() {
            console.log("I will be shared among all the objects.");
            console.log(this.initial + " " + this.end + " initial and end parameters are not shared among all objects. ")
      }
}
var obj = new C(19, 20);

This way seems pretty simple..Right?? Lets explore this too..

var C = function(initial, end) {
      this.initial = initial;
      this.end = end;
}

Here function c is constructor function. this refers to the newly created object. We know that each function has its prototype property defined. So,

C.prototype = {
      sharedMethod: function() {
            console.log("I will be shared among all the objects.");
            console.log(this.initial + " " + this.end + " initial and end parameters are not shared among all objects. ")
      }
}
We are assigning an object to C.prototype and that object has defined sharedMethod() function which will be shared among all the objects created from C constructor.

But, prototype property has some predefined variables set. If we will directly assign our object to C.prototype then we will end up loosing all predefined properties. So best practice is to set property of C.prototype like this:

C.prototype.sharedMedhod = function() {
      console.log("I will be shared among all the objects.");
      console.log(this.initial + " " + this.end + " initial and end parameters are not shared among all objects. ")
}

Coming to the predefined properties of prototype object..What is it? Any clue??? Well it is constructor property that matters.

C.prototype = {
      constructor: C
}

Whaaattt???? Well yes.. prototype property of C has another property constructor which points to the C constructor itself.
It has another property __proto__ which will point to its prototype object. In our case it will be Object object.

Lets play with it,

var F = function() {};      // This is a function object.
var p = F.prototype;      // This is the prototype object associated with it.
var c = p.constructor;      // This is the function associated with the prototype.
c === F                        // True.

I hope this post was helpful for you to understand Classes in JavaScript. ECMAScript 6 has easy way to define classes using class keyword. We will cover this also shortly.

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.