Why do you think that a is global? If your code is within a function then a is local, and alert (a) results in the value of a being alerted.
Code:
<script type="text/javascript">
test();
var a = 10;
function test() {
var a = 12; // note the var keyword defines a new variable local to the function. But it is obviously silly to duplicate names in this way.
alert ("Local " + a); //12
}
alert ("Global " + a); //10
</script>
if(true) is meaningless as the condition will always be true.
All advice is supplied packaged by intellectual weight, and not by volume. Contents may settle slightly in transit.
__________________
All the code given in this post has been tested and is intended to address the question asked.
Unless stated otherwise it is not just a demonstration.
<script type="text/javascript">
test();
var a = 10;
function test(){
if(true) {
var a = 40;
}
alert (a); // within the function alerts '40', not the global value of '10'
}
alert (a); // outside the function alerts global value of '10'
</script>
__________________
All the code given in this post has been tested and is intended to address the question asked.
Unless stated otherwise it is not just a demonstration.
i understand the example u showed me.but in the code i showed above,i think 'a' is a local variable,so in my opinion,alert(a) should pop up 'undefined' or sth,but it's '2',that's what confused me.
i understand the example u showed me.but in the code i showed above,i think 'a' is a local variable,so in my opinion,alert(a) should pop up 'undefined' or sth,but it's '2',that's what confused me.
If your code fragment is not contained within a function then the variable a is global scope. Do what I say - study the topic.
__________________
All the code given in this post has been tested and is intended to address the question asked.
Unless stated otherwise it is not just a demonstration.