-1

Why is the global variable some_var changed inside the if block in this example?

<script>
    var some_var = 0;

    var i = 5;
    if (i>2)
    {
        var some_var = 2;
    }
    else
    {}

    console.log(some_var);
</script>
Boann
  • 48,794
  • 16
  • 117
  • 146
mrgloom
  • 20,061
  • 36
  • 171
  • 301
  • take a look https://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var-to-declare-a-variable – Andrew Lohr Feb 13 '18 at 16:23
  • 1
    becasue an `if` block does not create a new scope.. it's in the same scope as an existing var with that name so the existing one gets overwrritten – I wrestled a bear once. Feb 13 '18 at 16:26
  • Also [What is the scope of variables in JavaScript?](https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript) – JJJ Feb 13 '18 at 16:31

1 Answers1

-3

I'm guessing that if you remove the 'var' inside the if block it works properly. Must be the environment checking for initializations before running the code.