Friday, December 23, 2011

Javascript Function Hoisting



There are differences how functions defined in javascript. In javascript all variable regardless of where in the function body declared will get hoisted to the top of function, this also includes  functions which are defined inside the function but there is a difference  how the functions has been declared. the example below shows this difference.


function foo() {

alert('global foo');
}
function bar() {

alert('global bar');
}
function hoistMe() {

console.log(typeof foo); // "function"
console.log(typeof bar); // "undefined"
foo(); // "local foo"
bar(); // TypeError: bar is not a function
// function declaration
function foo() {
alert('local foo');
}
//unnamed function expression
var bar = function () {
alert('local bar');
};
}
hoistMe();

in this example foo will get hoisted to the top with it’s definition but only declaration of bar has hoisted to the top.

3 comments:

  1. Very interesting article Bardia. I enjoyed it!

    ReplyDelete
  2. Thank you sir.I'm happy you enjoyed it.

    ReplyDelete
  3. Thank you Bardia - learned something new today.

    This is also a good post on hoisting:

    http://www.programmerinterview.com/index.php/javascript/javascript-hoisting/

    ReplyDelete