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.
Very interesting article Bardia. I enjoyed it!
ReplyDeleteThank you sir.I'm happy you enjoyed it.
ReplyDelete