-1

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");
}
Toma Radu-Petrescu
  • 2,152
  • 2
  • 23
  • 57

2 Answers2

0

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");
}
Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271
  • I'll blame caching in the mobile client then. – Makoto Jan 11 '17 at 23:38
  • 1
    Not just *function* declarations, *variable* declarations (not the initialization value) are hoisted to the top of their enclosing scope as well. So, `var f = function(){...}` will hoist as well. Not the value (the function), but the variable (`f`). – Scott Marcus Jan 11 '17 at 23:40
0

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.

Community
  • 1
  • 1
Peter Olson
  • 139,199
  • 49
  • 202
  • 242
  • Not just *function* declarations, all variable declarations are hoisted to the top of their scope as well. Not the assigned values, but the declarations. – Scott Marcus Jan 11 '17 at 23:47