The following test is successful and prints 1and 1:
function test1() {
a = 1;
console.log(a);
}
function test2() {
console.log(a);
}
test1();
test2();
And the following test fails because the local variable overrides the previously created global:
function test1() {
a = 1;
var a = 2;
console.log(a);
}
function test2() {
console.log(a);
}
test1();
test2();
Why does the second example permanently delete a global variable? What purpose / logic performs such functions in JavaScript?
EDITED: For those who flagged this as a duplicate Strange behavior for global and local variables in JavaScript
The upgrade refers to a scenario where a later declared local variable moves up the function area, overriding the previously visible variable. But in our case, the function first creates a global variable, and then deletes it completely / globally.
, , , :
function test1() {
a = 1;
console.log(a);
}
function test2() {
console.log(a);
var a = 2;
}
function test3() {
console.log(a);
}
test1();
test2();
test3();