Javascript Hoisting

JavaScript is an extremely flexible language, and will happily allow you to declare a variable almost anywhere. For example, the following immediately-invoked function expression (IIFE) declares three variables and then displays them using an alert dialog box. As a side note, you should never use alert boxes, but we’re trying to prove a point here.

1
2
3
4
5
6
7
(function() {
  var foo = 1;
  var bar = 2;
  var baz = 3;
  alert(foo + " " + bar + " " + baz);
})();

This looks like sane JavaScript code. As expected, it displays the string "1 2 3". Now, assume that the alert is moved, as shown below.

1
2
3
4
5
6
(function() {
  var foo = 1;
  alert(foo + " " + bar + " " + baz);
  var bar = 2;
  var baz = 3;
})();

If someone actually wrote this code, it was probably by mistake. Clearly, the alert takes place beforebar and baz are declared. However, this is perfectly valid JavaScript, which does not generate an exception. Instead, the alert displays "1 undefined undefined".

 

a;

b;

var a = b;

var b = 2;

b;

a;

console.log(a,b);

 

after compilation it converts the above code to below one..this is called hoisting..

 

var a;

var b;

a;

b;

a = b;

b = 2;

b;

a;

console.log(a,b);

 

another ex:

foo();

var foo=2;

function foo(){

console.log(“bar”);

}

function foo(){

console.log(“foo”);

}

//explanation: functions are moved to top before variables. Hence function foo will be moved and compiled then override with another foo function. Moving next to var foo=2 is ignored by compiler as function foo is already declared. Hence value foo is shown instead of 2/bar.

Eg: mutual recursive functions(2 or more functions calling each other)concept is impossible with out hoisting..thats the reason js language is implemented with hoisting while writing the language.

a(1);

function a(foo){

if(foo>20) return foo;

return b(foo+2);

}

function b(foo){

return c(foo)+1;

}

function c(foo){

return a(foo*2);

}

//answer is 39

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s