Reputation: 694
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
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