Thursday, January 7, 2016

Function Hoisting in JavaScript

Function Hoisting in JavaScript

clip_image001

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: })();

clip_image002l

This is because of JavaScript interpreter treats it in little different manner cause to function hoisting.so 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”.

Declaration

var x; // the declaration

Initialization

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.

Thanks

4 comments :

  1. Superb i got some valuable tips from here. Really its a amazing article i had ever read. I hope it will help a lot for all. Thank you so much for this amazing posts and please keep update like this excellent article

    Dotnet Training

    ReplyDelete
  2. I read your articles very excellent and the i agree our all points because all is very good information provided this through in the post. It is very helpful for me. Keep blogging like this. Thanks.


    SAP training in Chennai

    ReplyDelete
  3. Superb i got some valuable tips from here. Really its a amazing article i had ever read. I hope it will help a lot for all. Thank you so much for this amazing posts and please keep update like this excellent article.

    Selenium

    ReplyDelete
  4. Thanks for this blog. provided great information. All the details are explained clearly with the great explanation. Thanks for this wonderful blog. Step by step processes execution are given clearly.Know the details about different thing.
    Android Training in Chennai

    ReplyDelete