views:

101

answers:

3

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?

+1  A: 

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

Braveyard
No, no, no.You can try it. In same block, you can use function before its declaration.
Morgan Cheng
@Morgan : Sorry my mistake, I mistaken the function var hello = function(){} and function hello(). Thanks.
Braveyard
A: 

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
@Berry, how do you paste it into Firebug?You can paste it into a html and open it with Firefox. I bet it would work.
Morgan Cheng
Firebug has a debug console, where you can execute custom code inside your own context.
LiraNuna
+1  A: 

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";
}());
CMS