Thursday, January 7, 2016

Function Hoisting in JavaScript

Function Hoisting in JavaScript


Function hoisting is one of the fundamental point to understand in Java Script.I found it key point to understand shared my understanding on this :

Here I have a function defined below :

1: var x = 1234;

2: (function verify() {

3: document.write(x);

4: })();

When I run this code snippet it displays value as 1234 as an output.

However when I make any amendments to this function and create a variable x with some different value it still displays an output “undefined” value:

1: var x = 1234;

2: (function verify() {

3: document.write(x);

4: var x =4444;

5: })();


This is because of JavaScript interpreter treats it in little different manner cause to function what is function hoisting ?

Hoisting ==> Initialization is not hoisted only declaration is hoisted on the top of function means variable are defined at the top of the function but not initialize value.Hoisting actually mean “Move from one place to another by lifting”.


var x; // the declaration


x= 4444; // the initialization

The above given code would be treated like this at runtime as shown below:

1: var x = 1234;

2: (function verify() {

3: var x;

4: document.write(x);

5: x = 4444;

6: })();

if you notice in above code, only variable x declaration (var x; ) is at the top of function Verify() though an assignment or initialization of value is just below to document.write(x); This is the only reason it displays undefined as x doesn’t have any value.

Hope it will help you to understand hoisting.