tags:

views:

60

answers:

3

This is probably a nub question, but I don't understand why this works:

<script type="text/javascript">
    alert(foo);
    function foo() { }
</script>

This alerts "function foo() { }", but I expected the alert to be evaluated before the function foo was defined. Can someone explain what I don't understand about parse/evaluation order or point me to a resource that does?

Thanks in advance,

-- Breck

+2  A: 

JavaScript, like PHP, tracks top-level function declarations before the code runs. However, you can bypass the auto-function by using assignments:

var a = function a() { }

SHiNKiROU
Just a note, the function will still be hoisted before the `var` declaration on IE due a serious [bug](http://groups.google.com/group/comp.lang.javascript/msg/5b508b03b004bce8) present on all JScript versions, because the function expression is named.
CMS
@CMS Interesting little note. Does this affect all versions of IE?
alex
@alex, yes **ALL** versions of IE, including IE 9 Platform Preview! (I was really disappointed), the bug is even worse than that, it creates two function objects e.g. `var foo = function bar () {}; alert(foo===bar); //false!`
CMS
@CMS Oh, typical IE. Just wondering, how did you link in that comment. I tried using HTML and it didn't work.
alex
@alex, Nope, using Markdown e.g. `[link text](http://url)`
CMS
A: 

A must read about the types of function definitions in JavaScript.

Named Function Expressions Demystified

InfinitiesLoop
A: 

Function declarations are hoisted to the top, and therefore declared first and foremost.

You can change this behavior by assigning them to a variable like so

var a = function() {
   // do it
};

This assigns the variable a to an anonymous function.

alex