Q:

Variable declaration warning in VS2008

The following code in VS2008 gives me a "variable is already defined" warning:
if (someVar) {
  var a = 1;
}
else {
  var a = 2;
}

The warning is given on the second var a = .... To cure this warning I have done:
var a;
if (someVar) {
  a = 1;
}
else {
  a = 2;
}

But is this the correct way to do it?
Thanks,
AJ

A:

Yes, that is the correct way to do it. There is no block scope in javascript; there is only function scope and global scope.
you could also give each "block" functional scope using anonymous functions, although it's not very practical in this case:
if (someVar) {
  (function () {
     var a = 1;
   })();
}
else {
  (function () {
     var a = 2;
   })();
}

As a side note, this is also why for (var i = 0; ...) is discouraged in favor of var i; for (i = 0; ...), to avoid 2 consecutive loops in the same function both trying to declare the variable i

