Local vs. global variables in JavaScript. An example of a subtle bug.

Developers know the difference between a local and a global variable. The definition is mostly the same in the programming languages. In some languages expected behavior actually do not happen.

Here’s an example in JavaScript:

   1: var a = 123;
   2: function foo()
   3: {
   4:   alert(a);
   5:   var a = 890;
   6:   alert(a);
   7: }
   9: foo();


A lot of developers expect the first alert to display 123 and the second to display 890. Actually the first alert displays undefined. That’s because the local scope of the variable ‘a’ takes precedence over the global one in the function even if its first use appears before its declaration.

For this reason and for better code clarity, it’s best to name all global variables differently than all local ones.

You can test this at http://jsbin.com/odofu3/edit.