Functions are hoisted first, then variable declarations, per ECMAScript 5, section 10.5 which specifies how hoisting happens:
We first have step 5 handling function declarations:
For each FunctionDeclaration f in code, in source text order do…
Then step 8 handles var
declarations:
For each VariableDeclaration and VariableDeclarationNoIn d in code, in source text order do…
So, functions are given higher priority than var
statements, since the later var
statements cannot overwrite a previously-handled function declaration.
(Substep 8c enforces the condition “If varAlreadyDeclared is false, then [continue…]” so extant variable bindings are not overwritten.)
You can also see this experimentally:
function f(){}
var f;
console.log(f);
var g;
function g(){}
console.log(g);
Both log
calls show the function, not an undefined
value.