3

With the following JavaScript

if (someCondition){
   var x = ...; //Resharper warns that this is a duplicate declaration
}
else {
   var x = ...; //Resharper warns that this is a duplicate declaration
}

But the scopes are different? Why does this matter? Is this exclusive to JavaScript?

I get no such warning with equivalent code in C#.

Or -- Is it an erroneous Resharper warning?

Matt
  • 25,943
  • 66
  • 198
  • 303
  • 1
    Javascript does not have block scope. All declarations of `x` belong to the function in which they are declared. http://stackoverflow.com/questions/17311693/why-does-javascript-not-have-block-scope – aebabis May 26 '14 at 21:41

1 Answers1

6

Variables in JavaScript are by default bound to function scope, not to block scope. Variables defined inside blocks are hoisted to function scope, which is a very common source of errors. and exactly what happens in your case too.

Variables can be declared in block scope with let keyword although this requires JavaScript 1.7.

jsalonen
  • 29,593
  • 15
  • 91
  • 109