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

Wednesday 28 December 2016

Linked list in JavaScript

Most taught data structure in computer science is linked list. Among that, singly linked list is most commonly used. Most of the JavaScript newbies or the "Back-end web developers" implements almost everything using Arrays. Here in this post I will be showing another alternate yet quick way (using linked list) to solve few real life problems in JavaScript.

Linked list -


Image explains a lot, each node in a linked list holds two items, first item is the data while the other one is the pointer to the next item.

There are a few catches you might want to know -

  • Suppose there are 10 nodes in a linked list (numbered 1 to 10). If the pointer of node 1 is changed to 3 instead of 2 (1 ---> 3 ---> 4 ---> 5 so on..) then JavaScript garbage collector will free the memory space of node 2 since node 2 has no references
  • Linked list allows insertion or deletion of node at any place but does not allow random access
  • Linked list is a sequential access data structure. It will cost you a lot to find the element at the 6th position or 5th position or nth position
  • Use Linked list when you want to insert or delete an element where you have a huge amount of data, that's where Array will cost you a lot

Before moving forward, do you remember your training on object references, Luke? Well, you might want to recall how object references works in JavaScript -
var movie = {
    name: 'Star wars',
    rating: 8.5
}

var item = movie;

item.rating = 9;

console.log(movie.rating);


You guessed it right, it will print 9. There is only one memory space which is being referenced by both movie and the item variables. It really doesn't matter, through which variable you are changing that memory's value. This concept will benefit us while creating a linked list.


Implementation of Linked List -

A simple node -

var node1 = {
    data: null,
    next: null
}


We can assign some data to it -
node1.data = 'Empire strikes back';


Creating next node

var node2 = {
    data: null,
    next: null
}
node2.data = 'Return of the jedi';
node1.next = node2;


Pretty easy! Right? Of course, manually creating a node each time when needed is not the solution that we are looking for. A better way is to create a List object, which implements all the internal logic of the linked list and only exposes some utility methods for the user.

function List() {
    this.head = null;
    this.end = null;
}
Initially Linked list's head and end properties are set to null. That means the list is empty.


Now it should expose a method that can easily create a node

this.createNode = function() {
    return {
        data: null,
        next: null
    }
}

Next thing should be adding this newly created node in our existing list. While adding the new node in the list, you must consider a few things -

  • By default, new node should always be added at the end of the list
  • Before adding new element there should be a check of empty list. if empty, new element should be added at the beginning of the list


Adding node in the list -

this.addNode = function(data) {
    // Checking if list is empty
    if (this.start === null) {
        // Creating a new node
        this.head = List.createNode();
        // since we have only one node in list, start and end will point to same node
        this.end = this.start;
    } else {
        // Appending newly created node after the end of the list
        this.end.next = List.createNode();
        // Setting last node as end node
        this.end = this.end.next;
    }
    // Finally assigning data to the newly created node
    this.end.data = data;
}

so far your List function looks like -

function List() {
    this.head = null;
    this.end = null;

    this.createNode = function() {
        return {
            data: null,
            next: null
        }
    }

    this.addNode = function(data) {
        // Checking if list is empty
        if (this.start === null) {
            // Creating a new node
            this.head = List.createNode();
            // since we have only one node in list, start and end will point to same node
            this.end = this.start;
        } else {
            // Appending newly created node after the end of the list
            this.end.next = List.createNode();
            // Setting last node as end node
            this.end = this.end.next;
        }
        // Finally assigning data to the newly created node
        this.end.data = data;
    }
}


Now you can create the linked list with multiple nodes dynamically -

var list = new List();
for (var x = 0; x < 5; x++) {
    list.addNode(x);
}

Now that you have base structure ready, you can add multiple methods to your list.

Adding node at start of the list -

this.appendAtFirst = function(data) {
    var tempNode = List.createNode();
    tempNode.next = this.head;
    this.head = tempNode;
    tempNode.data = data;
}


Inserting after a node -

Inserting in between the linked list is way too easier as compared to array. Why you ask? Because array moves a lot of data in order to make space for new node while the linked list will simply changes pointer of one node. So, when you are dealing with huge amount of data that requires insertion and deletion, better to prefer linked list over array.

this.insertAfter = function(n, data) {
    // n: node after which data to be inserted
    var instance = this.head;
    // Start traversing from the first/head element until you reach nth node
    while (instance !== null) {
        if (instance.data === n) {
            var tempNode = List.createNode();
            tempNode.data = data;
            tempNode.next = instance.next;
            if (instance == this.end) {
                this.end = tempNode;
            }
            instance.next = tempNode;
            return;
        }
        instance = instance.next;
    }
}


Removing a node -

For removing any node, you just need to change the pointer of it's previous node to point to it's next node. After this, your node will not be having any reference. JavaScript garbage collector will delete that node for you. So no need to explicitly delete any element.

this.remove = function(data) {
    // data - Node having data needs to be deleted
    var instance = this.head;
    var previous = this.head;
    // Traverse list from head/start node
    while (instance !== null) {
        if (data === instance.data) {
            if (instance === this.start) {
                this.head = instance.next;
                return;
            }
            if (instance == this.end)
                this.end = previous;
            previous.next = instance.next;
            return;
        }
        previous = instance;
        instance = instance.next;
    }
}


List traversal -

Now it is easy to figure out how to traverse a list.

this.traverse = function() {
    var instance = this.head;
    while (instance !== null) {
        console.log(instance.data);
        instance = instance.next;
    }
}


Follow this blog for more JavaScript hacks!

Monday 7 March 2016

Understanding ECMAScript 6


If you are a web developer than you already know what ECMAScript is. For rest of the readers, let me introduce you with it. ECMAScript is trademark scripting language specification which is standardized by Ecma International. Languages like JavaScript, JScript, ActionScript follows ECMAScript specifications. Also, these languages provide some additional features not included in specifications yet. Till date, 6 versions of ECMAScript standards has been released and 7th's work is in progress.



Earlier posts from this blog were completely based on ES5 and now I am introducing you with some new, cool features of ES6.

Constants


We have seen in this post how we can create properties of an object according to ES5:

var obj = {};
obj.createProperty({
      writable: false,
      configurable: false,
      enumerable: false,
      value: "Why everything is False :| "
});

Using above method, we can define property which can not be altered (because writable is false), not enumerable (child object will not iterate in for..in loop) and neither configurable (property can not be deleted with delete operator). This way is only and hell complicated to define attributes of a property.
Luckily, ES6 has introduced concept of constants. Constants are basically variables which can not be reassigned new content or can not be re-declared. Variable itself is immutable BUT if variable is assigned an object than that object can be altered later.

const PI = 3.141593;      // Assigns some value to PI variable.
PI = 5;      // Will not assign. Error: Re-assigning
console.log(PI);      // Still print 3.141593

Note


const obiWan = {
      side: "Light",
      padawan: "Anakin"
}
const obiWan = "What is wrong with this line";      // Error: Re-declaring
obiWan = {                        // Error: Re-assigning
      side: "Still Light.",
      padawan: "Darth Vader"
}
console.log(obiWan);      // It will still print old object because we are re-assigning object which won't work
obiWan.side = "Still Light.";      // This will work
obiWan.padawan = "Darth Vader"      // This will work too
obiWan.endResult = "Merges with force!!"      // Yup. This will also work.
console.log(obiWan);      // This will print altered object


Variable Block Scoping

JavaScript variables defined using var keyword only supports function level scoping. That is, variable will be accessible throughout the function no matter where it has been declared or defined within function. This is possible because JavaScript supports Hoisting. Hoisting means all the variable declaration will come up on the first line of function body no matter where in the body they are declared. But the definition will remain on the same line where it is.

var f = function() {
      function p() {
             // some code in p function
      }
      function q() {
             // some code in q function
      }
      var i = 10;
      var j = {}
}

Above code will be interpreted as

var f = function() {
      var i, j;                       // Hoisting: variable declaration will come up
      function p() {
             // some code in p function
      }
      function q() {
             // some code in q function
      }
      i = 10;
      j = {};
}

Hoisting helps in many situations but that does not suppress the need of block level scoping. ES6 has introduced a way to declare variable with block level scope using keyword let. When a variable is defined using keyword let instead of var then scope of that variable is within the block only. Block can be for loop, do..while, etc.

Lets take a scenario based on ES5

var separateI = [];
for (var i = 0; i <= 2; i++) {
      separateI[i] = function() { return i * 2 }
}
separateI[0]() === 0;      // False....Result: 6
separateI[1]() === 2;      // False....Result: 6
separateI[2]() === 4;      // False....Result: 6

Why??? Because value of i at the end will be 3 (in the last iteration of for loop. Refer Lexical Scoping for more information). How can we solve this problem? Using block level scoping.

let separateI = [];
for (let i = 0; i <= 2; i++) {
      separateI[i] = function() { return i * 2 }
}
separateI[0] === 0;      // True
separateI[1] === 2;      // True
separateI[2] === 4;      // True

This approach kind of replaces the need of closures here.

Function Block Scoping

Functions in ES5 only have function scoping, i.e., inner function will be visible in all over the scope of outer function. But ES6 has introduced a way where function's scope can also be set to the block only and not to whole outer function.

{
      function foo () { return 1 }
      foo() === 1      // True
      {
            function foo () { return 2 }
            foo() === 2      // True
      }
      foo() === 1      // True
}

This can be achieved in ES5 also, but with lot of functions.

(function() {
      var foo = function() { return 1 }
      foo() === 1      // True
      (function() {
            var foo = function() { return 2 }
            foo() === 2;      // True
      })();
      foo() ===1;       // True
})();

Classes

Ladies and gentlemen.. prepare yourself for the epic moment in history of web development..(Crowd cheering..fireworks explode...) Finally Classes are introduced in JavaScript.. We always used to implement classes by putting lots of efforts. We were never be able to use class as variable since it was a "reserved keyword" for "future use". Well, now we are living in future..future begins from  here..:D

Most typical way to define a class in JavaScript (before ES6):

var myClass = function(x, y) {
      this.x = x;
      this.y = y;
}
myClass.prototype = {
      toString: function() {
            return this.x + " " + this.y;
      }
}
myClass.prototype.constructor = myClass;

Class definition in ES6:

class myClass {
      constructor (x, y) {
            this.x = x;
            this.y = y;
      }
      toString() {
            return this.x + " " + this.y;
      }
}

I know..this one is hell easy..JavaScript has always been awesome but now it feels complete..
If we have classes then surely we will be having easier way of inheriting classes. Lets explore that too.

class anotherClass extends myClass {
      constructor (x, y, width, height) {
            super(x, y);            // Calls the constructor of super class
            this.width = width;
            this.height = height;
      }
}

Inheritance in earlier version:

var myClass = function(x, y) {
      this.x = x;
      this.y = y;
}
myClass.prototype = {
      toString: function() {
            return this.x + " " + this.y;
      }
}
myClass.prototype.constructor = myClass;
var anotherClass = function(x, y, width, height) {
      myClass.call(this, x, y);
      this.height = height;
      this.width = width;
}
var anotherClass.prototype = Object.create(myClass.prototype);
anotherClass.prototype.constructor = anotherClass;

For explanation of inheritance in ES5 refer this post.

There are more other features of ES6 like arrow function which makes closures hell easy, extended libraries and etc which we will cover shortly. Till then keep exploring.

Drop comments for any doubts.

Tuesday 1 March 2016

JavaScript Properties


In this post, we will talk about JavaScript properties, what is inheritance and enumerability.
There are 3 attributes of object's property: writable, enumerable and configurable. Earlier in this post we have seen how object can be created and initialized at the same time like this:

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

Here, foo is property of child object and it has writable and configurable attribute set. If writable is true, that property can be altered later else not. If configurable is true, that property can be deleted using delete operator else not. And finally if enumerable is true, property will be iterated using for..in loop in it's child objects.

Accessing Properties


Properties can be accessed through its own definition or from its prototype chain.If you are accessing a property from any object than first, object's definition will be searched, if property is not available over there then object's immediate prototype is searched, if not even available there too then prototype's prototype is searched. The search goes on until property is found or up to the highest prototype from prototype chain. But there are some methods defined if you want to iterate only object's own property or all the properties from prototype chain or enumerable properties etc.

Iterating all own properties


var obj = {
      a: "Property of obj"
}
Object.getOwnPropertyNames(obj);
obj.hasOwnProperty(a);
Object.getOwnPropertyDescriptor(obj, a);
obj.b = "Another Property";
obj[c] = "One more Property";
delete obj.c;
delete obj[b];
Object.defineProperty(obj, "foo", { enumerable: true, writable: true, configurable: false, value: "Awesome!" });

Above methods will be used for iterating/accessing all the properties defined by object itself and not inherited from its prototype.

Iterating own enumerable properties


Object.keys(obj);

Above method will be used for iterating all the enumerable properties defined in object defination itself.

Enumerable Inherited Properties


for(var key in obj) {
      console.log(key);
}

All object's properties and enumerable inherited properties.

All Inherited Properties


propName in obj;
obj.propName;
obj[propName];
Using above method, all properties can be accessed.

This was very small post which covered very simple topic. I hope you like it. Please drop your comments.

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.