-2

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.

Elegant.Scripting
  • 757
  • 4
  • 10
  • 28
  • possible duplicate of [What is the function of the var keyword and when to use it (or omit it)?](http://stackoverflow.com/questions/1470488/what-is-the-function-of-the-var-keyword-and-when-to-use-it-or-omit-it) – Marty Jan 27 '15 at 03:50
  • JavaScript does not have block scope for variables. So putting `var` inside or outside of a loop does not matter. – PM 77-1 Jan 27 '15 at 03:50

3 Answers3

4

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.

andrusieczko
  • 2,824
  • 12
  • 23
  • Thanks Andrusie! So in most cases it is absolutely necessary to include the var keyword when creating a for loop, right? – Elegant.Scripting Jan 27 '15 at 03:53
  • If not declared and without `use strict` It will be [`hoisted`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var). Also, `window` object exists only inside browser. – PM 77-1 Jan 27 '15 at 03:54
  • yes, it is recommended not to pollute the global scope; you can try to use some type checkers like jshint or jslint - they'll give you some warnings about such code – andrusieczko Jan 27 '15 at 03:56
  • it's also good to use the strict mode: http://stackoverflow.com/questions/1335851/what-does-use-strict-do-in-javascript-and-what-is-the-reasoning-behind-it – andrusieczko Jan 27 '15 at 03:56
  • @PM77-1: you're right with `window` object, I shouldn't simplify that much; but "if not declared and without use strict It will be hoisted. " -> are you sure? if you use `use strict` then it throws an error, otherwise it's defined in the global scope IMHO – andrusieczko Jan 27 '15 at 04:05
  • I made a too broad of a statement regarding `hoisting`. You're correct. Sorry about that. – PM 77-1 Jan 27 '15 at 20:05
0

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.

Gabriel Garcia
  • 1,000
  • 10
  • 11
-2

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!

Erik Likeness
  • 97
  • 1
  • 2