Edu Felipe Edu Felipe - 1 month ago 5
Javascript Question

Why can I use a function before it's defined in Javascript?

This code always works, and across browsers:

function fooCheck() {

return internalFoo();

function internalFoo() { return true; }

I could not find a single reference to why it should work, though.
I first saw this in John Resig's presentation note, but it was only mentioned. There's no explanation there or anywhere for that matter.

Could someone please enlighten me?


The function declaration is magic and causes its identifier to be bound before anything in its code-block* is executed. This differs from an assignment with a function expression which is evaluated in normal top-down order, so if you changed the example to say:

var internalFoo = function() { return true; };

it would stop working. The function declaration is syntactically quite separate from the function expression, even though they look almost identical and can be ambiguous in some cases.

This is documented in the ECMAScript standard, section 10.1.3. Unfortunately ECMA-262 is not a very readable document even by standards-standards!

*: the containing function, block, module or script.