AJ.
AJ.

Reputation: 11240

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

Upvotes: 0

Views: 73

Answers (3)

cobbal
cobbal

Reputation: 70753

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

Upvotes: 4

Andy E
Andy E

Reputation: 344605

Either way is perfectly valid and fine (both examples ensure that the variable is declared with the var keyword), but generally it's best practice to declare your vars at the top of the current code block, as in your second example.

Upvotes: 0

Bravax
Bravax

Reputation: 10493

It depends on how you're using those variables afterwards.

If they relate to the same object, then it's the correct way.

If they relate to different objects, then I'd rename the variables, as this would prevent maintenance issues in the future.

Upvotes: 1

Related Questions