Why does local variable kill my global variable?

浪子不回头ぞ 提交于 2019-11-28 22:51:21

In javascript, you should know there is something called as HOISTING.

What this essentially means is, when you declare any local variables, the variable declaration is automatically carried to top of the scope.

eg:-

var globalId='10';
function check(){
alert(globalId); var globalId; }
check(); 

Changes to -

var globalId='10';
function check(){
var globalId;
alert(globalId);}
check(); 

Since globalID is still not assigned any value, it returns undefined in your output. The local variables always get priority over the global variables with same name.

Yes, all variables declared anywhere in a function are local to that function and exist throughout the function's code; they will be used in preference to globals of the same name.

From https://developer.mozilla.org/en/JavaScript/Guide/Values,_Variables,_and_Literals#Variable_Scope :

JavaScript does not have block statement scope; rather, it will be local to the code that the block resides within. [...] Another unusual thing about variables in JavaScript is that you can refer to a variable declared later, without getting an exception. This concept is known as hoisting; variables in JavaScript are in a sense "hoisted" or lifted to the top of the function or statement.

In your second portion of code, the local variable masks the global one.

var globalId='10';

function check() {
    // Your are defining a local variable in this function
    // so, the global one is not visible.
    alert(globalId);
    var globalId;
}

check(); 


The fact that yopur var statement is at the end of the function's definition doesn't change anything : the global variable is masked for the whole function.

So, for the whole execution of the function, the globalId variable will reference the local one, and not the global one.

Outside of that function, though, the global variable will still exist -- it will just not be seen from inside the function, because of the var statement.

As has been said, conforming to JavaScript scoping rules, the local variable masks the global for the entire function. However the global variable may be accessd, try the following

var globalId='10';

function check() {
    // Your are defining a local variable in this function
    // so, the global one is not visible.
    alert('Local : ' + globalId + ', Global : ' + window.globalId);
    var globalId;
}

check(); 

you declare NEW variable globalId inside function scope, so its undefined and this is correct. And no, it's not kill your global variable, you can check it by adding alert(globalId); after check(); call.

as if Javascript first executed the whole function, just to see if any variables 'might' be declared

this is the answer, more or less. The JavaScript interpreter looks for variable declarations within each scope, then "moves them" to the top of the scope.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!