0

Below is valid javascript code:

<script>
  foo();

  function foo()
  {
    alert("foo");
  }
</script>

The function foo is invoked before its declaration. So, I think browser must load the whole block script before its execution. By "whole block", I mean a open tag to a clos tag or a external javascript file. Is this true?

Morgan Cheng
  • 73,950
  • 66
  • 171
  • 230

3 Answers3

2

Function statements are subject to hoisting. This means that regardless of where a function is declared, it is moved to the top of the scope in which it is defined.

(function () {
  foo();

  function foo() {
    alert('foo is beign called');
  }
}());

At compile time the structure of that code would change to:

(function () {
  function foo() {
    alert('foo is beign called');
  }

  foo();
}());

Function statements are not the only that are subject of hoisting, the var statement also, because of that (and because JavaScript haves only function-scope) is recommended to have only one var statement at the top of a function, for example:

var bar = "baz"; // on the outer scope
(function () {
  alert(bar); // bar is undefined

  var bar = "other value";
}());

The alert shows undefined, because internally the code changed to this:

var bar = "baz";
(function () {
  var bar;
  alert(bar); // bar is undefined

  bar = "other value";
}());
Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
1

If a method or variable is undefined, it throws an error "undefined" but if it is declared but not assigned a value then js won't throw any error.

<script>
  foo();

  function foo()
  {
    alert("foo");
  }
</script>

But your code will not throw any exception and also you can debug your javascript code easily. Here is a nice video shows how to debug js codes : Debugging with Firebug

Tarik
  • 79,711
  • 83
  • 236
  • 349
0

When I paste that JS into Firebug, I get "foo is not defined".

Most implementations of JS will load the entire file, and then execute it. The statements in the file are executed in order, so the call to the function foo occurs before its definition, which is an error as required by the ECMA 262 standard section 8.7.1

Berry
  • 1,719
  • 2
  • 11
  • 15