Surprised that global variable has undefined value in JavaScript

后端 未结 6 1014
情话喂你
情话喂你 2020-11-22 01:33

Today, I got completely surprised when I saw that a global variable has undefined value in certain case.

Example:

var value = 10;
functi         


        
6条回答
  •  别那么骄傲
    2020-11-22 02:40

    There is a global variable value, but when control enters the test function, another value variable is declared, which shadows the global one. Since variable declarations (but not assignments) in JavaScript are hoisted to the top of scope in which they are declared:

    //value == undefined (global)
    var value = 10;
    //value == 10 (global)
    
    function test() {
        //value == undefined (local)
        var value = 20;
        //value == 20 (local)
    }
    //value == 10 (global)
    

    Note that the same is true of function declarations, which means you can call a function before it appears to be defined in your code:

    test(); //Call the function before it appears in the source
    function test() {
        //Do stuff
    }
    

    It's also worth noting that when you combine the two into a function expression, the variable will be undefined until the assignment takes place, so you can't call the function until that happens:

    var test = function() {
        //Do stuff
    };
    test(); //Have to call the function after the assignment
    

提交回复
热议问题