-1
function a(){
     var x,y,a,b;
     var a=2;
     var b=2;
     if (true) {
         var a,b;
         b=1;
         a = 1;
     }
     alert(a)
}
a();

Why the result is not 2? I wonder why redeclaration of a and b in if condition does not create a new variable a and b? Is there any rule I can follow?

Adam Azad
  • 11,171
  • 5
  • 29
  • 70
william007
  • 17,375
  • 25
  • 118
  • 194
  • 6
    javascript doesn't have block scope... it has only function scope(except when using [let](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/let)) - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Variable_scope – Arun P Johny Jan 07 '16 at 08:54
  • @ArunPJohny Sure it does, that's what `let` is for. – Madara's Ghost Jan 07 '16 at 08:55
  • 3
    Possible duplicate of [What is the scope of variables in JavaScript?](http://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript) – Ieuan Stanley Jan 07 '16 at 08:56
  • @MadaraUchiha already mentioned in the comment... see the content inside `()`, edited to add links – Arun P Johny Jan 07 '16 at 08:57
  • function and variable declarations are hoisted to the top of the enclosing function. Thats why redeclaration has no effect. – blessanm86 Jan 07 '16 at 08:58
  • Maybe i dont get the question. So you are using a if statement and it works. If the statment is true it give "a" a new value, if not it will leave 2 as value of "a" – Giova.panasiti Jan 07 '16 at 09:00
  • https://jsfiddle.net/xfa7bL05/ I used a>b in the if statment so it's false. When it is false it doest reassign a new value to the variable and you get "2" in the alert – Giova.panasiti Jan 07 '16 at 09:02

2 Answers2

0

In javascript, variables declared with var are hoisted to the top of the function. This means that the scope rules you are expecting do not work. This is addressed in the ES6 standard with the let keyword which will scope how you were expecting. See the following site for more info on let. You should note that the ES6 standard is new and is not widely supported. You can use the standard now by using a transpiler such as Babel. You can play with this on playgrounds such as codepen.

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/let

Lew
  • 1,248
  • 8
  • 13
0

"var" will create local variable in current scope, but as the scope in javascript is function level, and in the snippet mentioned we are in the same function, javascript interpreter thinks that variable declaration inside if block is re-declaration of the same variable in the same function scope.

null1941
  • 972
  • 8
  • 20