Variable scope in Javascript for loop

前端 未结 3 423
佛祖请我去吃肉
佛祖请我去吃肉 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:48

    The first example will either add or modify the global variable x, which is generally to be avoided if not the desired outcome.

    While your second example works as desired (no side effects) an alternative that looks better in my opinion would be

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

提交回复
热议问题