Reputation: 25840
The following test is a success, and prints 1
and 1
:
function test1() {
a = 1;
console.log(a); // prints "1"
}
function test2() {
console.log(a); // prints "1"
}
test1();
test2();
And the following test fails, because a local variable overrides the previously created global one:
function test1() {
a = 1;
var a = 2;
console.log(a); // prints "2"
}
function test2() {
console.log(a); // throws an error
}
test1();
test2();
Why does the second example remove the global variable permanently? What purpose/logic does such functionality serve in JavaScript?
EDITED: For those who marked it as a duplicate of Strange Behavior on Global and Local Variable in JavaScript
Hoisting refers to the scenario when a later declared local variable is moved up the function scope, overriding the previously visible variable. But in our case the function first creates a global variable, and then deletes it completely/globally.
However, it is probably related, as we can see in the following test:
function test1() {
a = 1;
console.log(a); // prints "1"
}
function test2() {
console.log(a); // prints "undefined"
var a = 2;
}
function test3() {
console.log(a); // prints "1"
}
test1();
test2();
test3();
Upvotes: 4
Views: 638
Reputation: 115950
In your second case, no global variable named a
ever exists.
a = 1
generally does not create a global variable. The statement a = 1
stores the value 1
in a variable called a
. If the variable environment of any containing local scope has a variable called a
, the nearest scope with an a
variable will have that variable set to 1
.
As a special case, if a variable called a
does not exist in any containing scope (and if you are not in strict mode), then the JavaScript engine will create a global variable called a
.
In your second case, var a
creates an a
variable in the local scope. Due to hoisting, that modification to the scope's variable environment happens before any code runs. Thus, by the time a = 1
is executed, that local scope does have a variable called a
, so that local variable is used.
In your third case, test2
logs the local variable a
(created by the var a
). At the time the log
call is made, the local a
has not yet been assigned a value.
Hoisting refers to the scenario when a later declared local variable is moved up the function scope, overriding the previously visible variable.
Hoisting simply means that all var
declarations are treated as if they happen at the top of their containing function. It has nothing to do (directly) with overriding variable visibility.
Note that declarations with an assignment will have only the declaration hoisted, not the assignment. The assignment stays in place wherever it is in the function.
Upvotes: 2
Reputation: 6746
Javascript moves variable declarations to the top. So in this example the compiler reads you code as:
function test1() {
var a;
a = 1;
a = 2;
console.log(a); // prints "2"
}
function test2() {
console.log(a); // throws an error
}
test1();
test2();
Upvotes: 1