Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>From <a href="http://javascriptweblog.wordpress.com/2010/07/06/function-declarations-vs-function-expressions/" rel="noreferrer">http://javascriptweblog.wordpress.com/2010/07/06/function-declarations-vs-function-expressions/</a></p> <p>In javascript, you have function declaration:</p> <pre><code>function foo() { } </code></pre> <p>and function expression</p> <pre><code>var foo = function() { } </code></pre> <p>Quoting from <a href="http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting" rel="noreferrer">http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting</a></p> <blockquote> <p>“Function declarations and function variables are always moved (‘hoisted’) to the top of their JavaScript scope by the JavaScript interpreter”.</p> </blockquote> <p>So what happened in your first example is that function declaration of <code>function a()</code>, gets hoisted to the top of the Javascript scope, thus producing 'foo' even though the if evaluates to false</p> <p>Think of <code>var foo</code> as a normal Javascript statement, it's only executed on the runtime of your javascript, unlike <code>function foo()</code>, that's why the below is valid:</p> <pre><code>alert(foo()); function foo() { return 'gw ganteng'; } </code></pre> <p>Here, <code>function foo()</code> is parsed by the parser, putting <code>foo()</code> in the current scope, before attempting to call <code>alert(foo())</code></p> <p><a href="http://javascriptweblog.wordpress.com/2010/07/06/function-declarations-vs-function-expressions/" rel="noreferrer">http://javascriptweblog.wordpress.com/2010/07/06/function-declarations-vs-function-expressions/</a></p> <blockquote> <p>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.</p> </blockquote>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload