Vladyslav Lubenskyi
Vladyslav Lubenskyi

Reputation: 694

Why JavaScript declares local variable before function is actually invoked?

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?

Upvotes: 0

Views: 51

Answers (2)

Quentin
Quentin

Reputation: 943643

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.

Upvotes: 1

Naftali
Naftali

Reputation: 146310

It is called variable hoisting.

Here is the documentation on it

Upvotes: 4

Related Questions