0
function test()
{
    i = 10;
    for (var i = 0; i < 1; i++);
    alert(i);
}

I've tested this in Firefox. Does it give the same result in all browsers? Is the i in the for statement header local to the for statement or to the function?

Henrik3
  • 27
  • 4
  • what are you trying to doing? – ferhado Oct 26 '17 at 19:00
  • hoisting, learn about it. https://developer.mozilla.org/en-US/docs/Glossary/Hoisting and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var – epascarello Oct 26 '17 at 19:02
  • To the function. Read a tutorial. – ASDFGerte Oct 26 '17 at 19:02
  • 1
    `var` are function scoped, you will want to use `let` for `for` scope. – Keith Oct 26 '17 at 19:02
  • @Keith Is var function scoped even when inside a block under the for statement? But let makes it for scoped, even as the code stands? – Henrik3 Oct 26 '17 at 19:06
  • a `var` is function scoped no matter what you do with it. – Keith Oct 26 '17 at 19:07
  • @Henrik3 `let` and `const` are `block` scoped, meaning within any { } – Nick Oct 26 '17 at 19:07
  • 1
    @snapjs If there wasn't another `var` later it would be global. But the `var` that's there get's hoisted. – Keith Oct 26 '17 at 19:08
  • @Henrik3 please go through this link https://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var-to-declare-a-variable – Himanshu Bansal Oct 26 '17 at 19:09
  • To make this easier to understand, the code is really `var i = 10; for (i = 0; i < 1; i ++)` so basically the `i=10` just becomes a no op.. – Keith Oct 26 '17 at 19:13
  • @snapjs Aha, so var is not like declaring local vars in C but let is? – Henrik3 Oct 26 '17 at 19:14
  • @Keith What does hoisted mean? I don't understand "becomes a no op". – Henrik3 Oct 26 '17 at 19:16
  • @Henrik3 can you see my code above, basically the `var` gets pushed to the top of the function. It's the reason `let` & `const` are here.. I can't think of any reason to use `var` anymore, `let` & `const` are the way to go. Before `let` / `const`, we had to create what are called closures.. eg.. `(function () { for(var i = 0; i < 1; i ++) {} }())` , here the `var` is local to the for loop, because it's local to the function closure. – Keith Oct 26 '17 at 19:19
  • @Keith Now I understand. It's quite simple, actually. In js there are only 2 kinds of vars: global and function local. That is, until let vars came along. Yes? – Henrik3 Oct 26 '17 at 19:23

1 Answers1

0

var is function scoped, therefore your function

function test()
{
    i = 10;
    for (var i = 0; i < 1; i++);
    alert(i);
}

will declare an i variable, override it with another one with similar name in a for, resulting in 1 and this value will be alerted.

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175