Global variable override with local

The following test is successful and prints 1and 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 the local variable overrides the previously created global:

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 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); // prints "1"
}
function test2() {
    console.log(a); // prints "undefined"
    var a = 2;
}
function test3() {
    console.log(a); // prints "1"
}
test1();
test2();
test3();
+4
2

a .

a = 1 . a = 1 1 a. a, a , 1.

, a - ( ), JavaScript a.

var a a . - . , a = 1 a, .

test2 a ( var a). log a .


, , .

, var , . () .

, , . , .

+2

Javascript . , :

function test1() {
    var a;
    a = 1;
    a = 2;
    console.log(a); // prints "2"
}
function test2() {
    console.log(a); // throws an error
}
test1();
test2();
+1

Source: https://habr.com/ru/post/1589230/


All Articles