Sunday, November 22, 2015

The Real JavaScript

Hi, In this article i am going to explain the internal architecture of the JavaScript object. After reading this article you have a clear understanding of JavaScript Object, what is __proto__ and prototype chaining in JavaScript.

lets start :)

There are three ways to create an object in JavaScript.

1. Using an object literal

var Person  = {};

2. Using the new keyword

var Person = new Object();

3. Inheriting Object.prototype

var Person = Object.create(Object.prototype);

All of these create same person object.
Here var Person = Object.create(Object.prototype); means that Person object extends from Object.prototype Object.

If you want to add some property to the Person object then this can be added as below.

Person.name = "deepak";

Now Person Object has one property name of type string and has value deepak in it.

So lets understand this simple object by structure.


In the above image you can see the structure of Person Object. Here Person Object extends from Object.prototype Object.

__proto__ provides link between the objects.

For a property it will look into the Object
if unable to find then it will look into the Object.__proto__
if unable to find it will look into the Object.__proto__.__proto__ and so on, until it find null, this is called prototype chaining in JavaScript.

Longer the prototype chain more the access time.

Here Person object accessing hasOwnProperty() method by prototype chaining.

Wednesday, November 4, 2015

What is IIFE in JavaScript

IIFE means Immediately Invoked Function Expression.
It is just an anonymous function that is wrapped inside of a set of parentheses and invoked immediately.
We use IIFE to place all our code inside of a local scope or to avoid global scope.

Structure of the IIFE


Example


In the above example, the code outside of the IIFE has a global scope and the code inside of the IIFE has a local scope. Any variables declared inside of an IIFE can not be assessed from the outside of that IIFE.
It is one of the best practice of JavaScript to avoid global variables and functions. There are lots of design patterns in which we can avoid global variables and functions, IIFE is one of them.

Link of program
IIFE Program