Reputation: 3964
Generally variables(Variable Declaration) declared inside a function can be accessed only by that function & its inner functions.But, Undeclared Assignment of a variable inside a function is accessed outside of the function Scope in JavaScript by making it a global variable. Why does this happen ?
var hello = function() {
number = 45;
};
hello();
console.log(number); // 45 is printed in the console
Upvotes: 0
Views: 86
Reputation: 887433
Because the spec says so.
Add "use strict";
to the top of your file or function to disallow this.
Upvotes: 1
Reputation: 413709
Assignments to variables that do not appear in var
declarations are treated as assignments to global variables (properties of the global context). In "strict" mode, such assignments raise an error.
That's just how JavaScript works. If number
were declared properly, it would not be visible globally:
var hello = function() {
var number = 45;
}
hello();
console.log(number); // undefined is printed in the console
Upvotes: 1