Variable declaration necessary in for loop?

2019-03-07 02:54发布

What is the difference between:

  • for (var i=0; i<5; i++) {}
  • for (i=0; i<5; i++) {}

And is it necessary to include the var keyword?

I understand that the var keyword affects variable scope, but I'm having trouble understanding if it's necessary to include the keyword in for loops.

3条回答
The star\"
2楼-- · 2019-03-07 03:15

I am assuming your are using C#, Java or JavaScript. The short answer is you need the var if "i" has not already been declared. You do not need if it has already been declared.

For example:

var i;
for(i=1;i<=5;i++) {}

Now there may be some implicit variable typing depending on language and IDE, but relying on implicit typing can be difficult to maintain.

Hope this helps, good luck!

查看更多
放我归山
3楼-- · 2019-03-07 03:19

1

for (var i = 0; i < 5; ++i) {
  // do stuff
}

2

var i;
for (i = 0; i < 5; ++i) {
  // do stuff
}

3

for (i = 0; i < 5; ++i) {
  // do stuff
}

1 and 2 are the same.

3 you probably never mean to do — it puts i in the global scope.

查看更多
forever°为你锁心
4楼-- · 2019-03-07 03:28

In the second example, your variable is defined globally, so if you're in the browser environment, you can access it from the window object.

The first one is an equivalent of:

var i;
for (i=0; i<5; i++) {}

as all the variables in javascript are hoisted to the beginning of the scope.

查看更多
登录 后发表回答