From http://javascriptweblog.wordpress.com/2010/07/06/function-declarations-vs-function-expressions/
In javascript, you have function declaration:
function foo() {
}
and function expression
var foo = function() {
}
Quoting from http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting
“Function declarations and function variables are always moved
(‘hoisted’) to the top of their JavaScript scope by the JavaScript
interpreter”.
So what happened in your first example is that function declaration of function a()
, gets hoisted to the top of the Javascript scope, thus producing 'foo' even though the if evaluates to false
Think of var foo
as a normal Javascript statement, it's only executed on the runtime of your javascript, unlike function foo()
, that's why the below is valid:
alert(foo());
function foo() {
return 'gw ganteng';
}
Here, function foo()
is parsed by the parser, putting foo()
in the current scope, before attempting to call alert(foo())
http://javascriptweblog.wordpress.com/2010/07/06/function-declarations-vs-function-expressions/
In JavaScript execution there is Context (which ECMA 5 breaks into
LexicalEnvironment, VariableEnvironment and ThisBinding) and Process
(a set of statements to be invoked in sequence). Declarations
contribute to the VariableEnvironment when the execution scope is
entered. They are distinct from Statements (such as return) and are
not subject to their rules of process.