Scope of Script Tags


Here is the simple test for you, assume that the following


<script type="text/javascript">
        var a = 3;
</script>

<script type="text/javascript">
        alert(a + 1);
</script>



What will be the result in the pop-up alert?



If you said browser will display an error like "a is not defined", you are wrong :) Browsers interpret all the script tags inside the page (also the imported .js files) in the same scope. Therefore, number a is a global variable and alert will display 4 in the pop-up.

Comments

Anonymous said…
So how does one include a remote script with a custom (non-global) scope?

Popular posts from this blog

Space Character Problem on IE 6, 7, and 8

AWS encryption chart (SSE-S3 vs SSE-KMS vs SSE-C)

Does Netflix work on iOS 5 Beta 4?