Why can the first anonymous function 'see' the functions under it such as foo
? Shouldn't it only see what it is above it? Thanks.
window.onload = function(){
foo();
}
function foo(){
alert("hello");
}
Why can the first anonymous function 'see' the functions under it such as foo
? Shouldn't it only see what it is above it? Thanks.
window.onload = function(){
foo();
}
function foo(){
alert("hello");
}
See function declaration hoisting:
Function declarations in JavaScript are hoisting the function definition. You can use the function before you declared it:
hoisted(); // logs "foo" function hoisted() { console.log("foo"); }
This is due to function hoisting. In JavaScript, function declarations are "hoisted" to the top of their scope, which, as you noticed, allows functions declared anywhere in the file to be called.