Surprised that global variable has undefined value in JavaScript

后端 未结 6 1006
情话喂你
情话喂你 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:14

    Variables in JavaScript always have function-wide scope. Even if they were defined in the middle of the function, they are visible before. Similar phenomena may be observed with function hoisting.

    That being said, the first console.log(value) sees the value variable (the inner one which shadows the outer value), but it has not yet been initialized. You can think of it as if all variable declarations were implicitly moved to the beginning of the function (not inner-most code block), while the definitions are left on the same place.

    See also

    • Javascript function scoping and hoisting
    • Javascript variable declarations at the head of a function

提交回复
热议问题