Sasank Sunkavalli
Sasank Sunkavalli

Reputation: 3964

Undeclared assignment of variables are accessed outside of the function scope in JavaScript?

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

Answers (2)

SLaks
SLaks

Reputation: 887433

Because the spec says so.

Add "use strict"; to the top of your file or function to disallow this.

Upvotes: 1

Pointy
Pointy

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

Related Questions