Variables in JavaScript are not defined in a block scope, but in a function scope
This means that if a variable is defined inside a function, it's not visible outside of the function.
However, a variable defined inside an if or a for code block is visible outside the code block.
The term "global variables" describes variables you define outside of any function.
It is also important to note that if you don't use var to declare a variable, this variable is automatically assigned global scope
>>> function f() { local = 2; }
>>> local
ReferenceError: local is not defined
>>> f ()
>>> local
2
The function f() contains the variable local. Before calling the function, the variable doesn't exist. When you call the function for the first time, the variable local is created with a global scope.
var a = 123;
function f() {
alert(a);
var a = 1;
alert(a);
}
f();
So a local variable overwrites any global variable with the same name
The first alert will show "undefined".
At the time of the first alert() a was not yet defined (hence the value undefined) but it still existed in the local space.
No comments:
Post a Comment