March 15, 2010
All the JavaScript books I read so far do not distinguish between following two ways of declaring a function.
var foo = function () {};
function foo() {}
Thanks to Ben today I learned that there is a difference .
function test() {
foo();
var foo = function () {
console.log("foo");
};
}
test();
Above code is same as one given below.
function test() {
var foo;
foo();
foo = function () {
console.log("foo");
};
}
test();
function test() {
foo();
function foo() {
console.log("foo");
}
}
test();
Above code is same as one given below.
function test() {
var foo;
foo = function () {};
console.log(foo());
}
test();
Now it will be clear why foo()
does not work in the following case while
bar()
does work.
function test() {
foo(); // TypeError "foo is not a function"
bar(); // "this will run!"
var foo = function () {
// function expression assigned to local variable 'foo'
alert("this won't run!");
};
function bar() {
// function declaration, given the name 'bar'
alert("this will run!");
}
}
test();
If this blog was helpful, check out our full blog archive.