Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to understand global and local variable in javascript [duplicate]

Tags:

javascript

1st test:

var a = 1;
function b() {
    a = 10;
    return;
    function a() {}
}
b();
alert(a);    // 1

2nd test:

var a = 1;
function b() {
    a = 10;
    return;
}
b();
alert(a);    // 10

In the first test, a is equal to 1, although I set it to 10 in the method. In the second test, I set it to 10 and it is set to 10 when I output it.. How does this work?

like image 780
Chen Xiaoshen Avatar asked Aug 01 '13 10:08

Chen Xiaoshen


1 Answers

The function declaration function a() {} declares a variable name a in the local scope of your b function (and assigns it the function). When you are assigning to a, you will assign to that local variable not the global one.

With hoisting applied, your code is equivalent to

var b = function b() {
    var a = function a() {};
    a = 10;
    return;
}
var a = 1;
b();
alert(a);    // 1, obvious now
like image 66
Bergi Avatar answered Sep 19 '22 23:09

Bergi