0

Easy example:

var b = function (msg) {
   (function inn() {
       console.log(msg);
       var msg = 0; 
   })();
} b("15");

This code will log 'undefined' because the local 'msg' on line #4 was declared before this line is actually executed. Are there any points in documentation on this?

5
  • 2
    Acutally, it would log -> Uncaught SyntaxError: Unexpected token ) Commented Jul 17, 2013 at 13:38
  • Yep, sure, I already fixed that :) Commented Jul 17, 2013 at 13:39
  • Now it would log -> Uncaught SyntaxError: Unexpected identifier Commented Jul 17, 2013 at 13:39
  • 1
    @VladLubenskiy you need b("15") on a new line or a ; after the function call Commented Jul 17, 2013 at 13:39
  • jsfiddle.net/UkFwe Commented Jul 17, 2013 at 13:41

2 Answers 2

4

It is called variable hoisting.

Here is the documentation on it

Sign up to request clarification or add additional context in comments.

Comments

1

The language specification says: 10.5 Declaration Binding Instantiation:

On entering an execution context, bindings are created in the VariableEnvironment as follows … For each VariableDeclaration and VariableDeclarationNoIn d in code … Call env’s CreateMutableBinding concrete method

MDN has a more readable explanation:

In JavaScript, variable can be declared after being used. For that reason, it is recommended to always declare variable at the top of functions. Otherwise, it may lead to confusing cases.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.