Thursday, October 24, 2019

javascript - Why does local variable kill my global variable?

Sorry for this question, but this issue really screwed up my day.



The following Code alerts 10 as it should:



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



But this next code alerts undefined:



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



I am aware that if I declare a variable in a function its a local variable, but if I already declared it as global, how can it be that my alerts says undefined?



This is an easy example, but in my original code I did a lot of stuff in between the beginning of the function, then a long way down I checked to see if globalId was defined, else define it: if(!globalId){var globalId;} This meant that my alert situated at the top of the function generated undefined, as if JavaScript first executed the whole function, just to see if any variables 'might' be declared, and if so, declare them and therefore my alert pointed to an 'undeclared' variable.



Can anybody explain to me why this happen, and if it is true that JavaScript "pre-declares" all variables before executing a function, even variables declared in conditions not even met?

No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...