1

The following javascript code

var variable = 1
console.log(variable)
{
    var variable = 2
}
console.log(variable)

gives the output

1
2

Given the way scopes work in other programming languages I find this very unintuitive. The redeclaration of variable inside the scope shouldn't affect the value of the variable outside the scope.

I tested this on Firefox and Chromium. Am I doing something wrong or is this the expected behavior of javascript?

As a reference, this is what happens in other programming languages:

#include<stdio.h>
int main() 
{
    int variable=1;
    printf("%i\n",variable);
    {
        int variable=2;
    }
    printf("%i\n",variable);

    return 0;
}

output:

1
1
Jonathan
  • 358
  • 3
  • 14
  • JavaScript doesn't have block scope. At least, not recently (see the answer). So both your declarations are actually in the same scope and there's no shadowing happening in your snippet like there is in c. Which is why you see the `(function() {...})();` pattern all over the place in JS. – Jared Smith Jun 28 '17 at 16:15
  • Thanks, I now updated my knowledge using [https://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var-to-declare-a-variable] – Jonathan Jun 28 '17 at 16:24
  • This resource is a very nice explanation of the different scopes in javascript: https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript#500459 – Jonathan Jun 28 '17 at 16:45

1 Answers1

1

With ES6, you could use let, which respects block scope

The let statement declares a block scope local variable, optionally initializing it to a value.

instead of var declaration.

var variable = 1;
console.log(variable);
{
    let variable = 2;
}
console.log(variable);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392