Variable scope in Javascript for loop

前端 未结 3 425
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-09 09:13

What\'s the difference between:

function bar()
{
  for (x=0; x< 100; x++) {}
}

And

function bar()
{
  var x;
  for (x=0;         


        
3条回答
  •  眼角桃花
    2020-12-09 09:59

    A variable is created at the time you declare/use it. If you omit the var keyword than the variable is created automatically in the global scope. So you produce a side effect. This is generally to be avoided.

    Assume you use global variables and then you chose the name of variable that some other piece of the software has already taken. This will lead to a situation where to pieces of code overwrite their values. This produces errors and is most of the time hard to debug. In your example you might overwriting a global variable x that another software is using.

    Using var is also faster. If you access a global variable it has to scan all scopes up to the global one for the variable name. By using var it is bound to your local scope.

    It is good practice to use always use var. Or better: it is always good to select the most narrowed scope for your variables. Now you have global and var. A var declaration is visible in the whole function no matter where you declare it. In javascript 1.7 there is new keyword introduced: let. Let narrows the scope even more. If you declare your for loop with

    for(let x = 0; x < 100; i++) {}
    

    than x is visible only inside the {} block.

提交回复
热议问题