Use var, it reduces the scope of the variable otherwise the variable looks up to the nearest closure searching for a var statement. If it cannot find a var then it is global (if you are in a strict mode, using strict, global variables throw an error). This can lead to problems like the following.

Copyfunction f (){
    for (i=0; i<5; i++);
}
var i = 2;
f ();
alert (i); //i == 5. i should be 2

If you write var i in the for loop the alert shows 2.

JavaScript Scoping and Hoisting

Answer from Gabriel Llamas on Stack Overflow
Top answer
1 of 10
110

Use var, it reduces the scope of the variable otherwise the variable looks up to the nearest closure searching for a var statement. If it cannot find a var then it is global (if you are in a strict mode, using strict, global variables throw an error). This can lead to problems like the following.

Copyfunction f (){
    for (i=0; i<5; i++);
}
var i = 2;
f ();
alert (i); //i == 5. i should be 2

If you write var i in the for loop the alert shows 2.

JavaScript Scoping and Hoisting

2 of 10
42

The first version:

Copyfor (var x in set) {
    ...
}

declares a local variable called x. The second version:

Copyfor (x in set) {
    ...
}

does not.

If x is already a local variable (i.e. you have a var x; or var x = ...; somewhere earlier in your current scope (i.e. the current function)) then they will be equivalent. If x is not already a local variable, then using the second will implicitly declare a global variable x. Consider this code:

Copyvar obj1 = {hey: 10, there: 15};
var obj2 = {heli: 99, copter: 10};
function loop1() {
    for (x in obj1) alert(x);
}
function loop2() {
    for (x in obj2) {
        loop1(); 
        alert(x);
    }
}
loop2();

you might expect this to alert hey, there, heli, hey, there, copter, but since the x is one and the same it will alert hey, there, there, hey, there, there. You don't want that! Use var x in your for loops.

To top it all off: if the for loop is in the global scope (i.e. not in a function), then the local scope (the scope x is declared in if you use var x) is the same as the global scope (the scope x is implicitly declared in if you use x without a var), so the two versions will be identical.

๐ŸŒ
W3Schools
w3schools.com โ€บ js โ€บ js_loop_for.asp
JavaScript for Loop
exp 3 increments the value of the initial variable (i++). ... exp 3 can do anything like negative increment (i--), positive increment (i = i + 15), or anything else. exp 3 can be omitted (if you increment the value inside the loop): const cars = ["BMW", "Volvo", "Saab", "Ford"]; let len = cars.length; let i = 0; let text = ""; for (; i < len; ) { text += cars[i] + "<br>"; i++; } Try it Yourself ยป
Discussions

Is it best to use "var" or "let" in for loop iterations or does it even matter?
Use let in for loops. The difference is that var is function scoped and let is block scoped. When you use var you will be able to access i anywhere in the function it's declared in, even outside of the for loop. Generally you only want to use i inside the for loop so it's better to use let. const shouldn't work because i++ implies you are reassigning the value of i. More on reddit.com
๐ŸŒ r/javascript
359
217
January 24, 2018
Var variable used in loops
Can someone explain to me more in detail why the console.log result here is 3? var printNumTwo; for (var i = 0; i More on forum.freecodecamp.org
๐ŸŒ forum.freecodecamp.org
0
0
June 6, 2020
why can't I use "var" in for loop
JavaScript JavaScript and the DOM (Retiring) Responding to User Interaction Listening for Events with addEventListener() ... When I use var in the for loop to set i = 0. I get errors. When I change it to "let" it works. I have not really learned about let so I always use var. More on teamtreehouse.com
๐ŸŒ teamtreehouse.com
2
September 15, 2017
performance - JavaScript variables declare outside or inside loop? - Stack Overflow
In AS3 I believe you should initialise all variables outside loops for increased performance. Is this the case with JavaScript as well? Which is better / faster / best-practice? var value = 0; fo... More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
MDN Web Docs
developer.mozilla.org โ€บ en-US โ€บ docs โ€บ Web โ€บ JavaScript โ€บ Reference โ€บ Statements โ€บ for
for - JavaScript | MDN - MDN Web Docs - Mozilla
Typically used to initialize a counter variable. This expression may optionally declare new variables with var or let keywords. Variables declared with var are not local to the loop, i.e., they are in the same scope the for loop is in.
๐ŸŒ
MDN Web Docs
developer.mozilla.org โ€บ en-US โ€บ docs โ€บ Web โ€บ JavaScript โ€บ Reference โ€บ Statements โ€บ for...in
for...in - JavaScript | MDN - MDN Web Docs
You can use const to declare the variable as long as it's not reassigned within the loop body (it can change between iterations, because those are two separate variables). Otherwise, you can use let. You can use destructuring to assign multiple local variables, or use a property accessor like for (x.y in iterable) to assign the value to an object property.
๐ŸŒ
freeCodeCamp
forum.freecodecamp.org โ€บ javascript
Var variable used in loops - JavaScript - The freeCodeCamp Forum
June 6, 2020 - Can someone explain to me more in detail why the console.log result here is 3? var printNumTwo; for (var i = 0; i < 3; i++) { if (i === 2) { printNumTwo = function() { return i; }; } } console.log(prinโ€ฆ
๐ŸŒ
Mozilla
developer.mozilla.org โ€บ en-US โ€บ docs โ€บ Web โ€บ JavaScript โ€บ Guide โ€บ Loops_and_iteration
Loops and iteration - JavaScript - MDN Web Docs - Mozilla
Here, the for statement declares the variable i and initializes it to 0. It checks that i is less than the number of options in the <select> element, performs the succeeding if statement, and increments i by 1 after each pass through the loop.
Find elsewhere
Top answer
1 of 13
305

There is absolutely no difference in meaning or performance, in JavaScript or ActionScript.

var is a directive for the parser, and not a command executed at run-time. If a particular identifier has been declared var once or more anywhere in a function body(*), then all use of that identifier in the block will be referring to the local variable. It makes no difference whether value is declared to be var inside the loop, outside the loop, or both.

Consequently you should write whichever you find most readable. I disagree with Crockford that putting all the vars at the top of a function is always the best thing. For the case where a variable is used temporarily in a section of code, it's better to declare var in that section, so the section stands alone and can be copy-pasted. Otherwise, copy-paste a few lines of code to a new function during refactoring, without separately picking out and moving the associated var, and you've got yourself an accidental global.

In particular:

for (var i; i<100; i++)
    do something;

for (var i; i<100; i++)
    do something else;

Crockford will recommend you remove the second var (or remove both vars and do var i; above), and jslint will whinge at you for this. But IMO it's more maintainable to keep both vars, keeping all the related code together, instead of having an extra, easily-forgotten bit of code at the top of the function.

Personally I tend to declare as var the first assignment of a variable in an independent section of code, whether or not there's another separate usage of the same variable name in some other part of the same function. For me, having to declare var at all is an undesirable JS wart (it would have been better to have variables default to local); I don't see it as my duty to duplicate the limitations of [an old revision of] ANSI C in JavaScript as well.

(*: other than in nested function bodies)

2 of 13
66

In theory it shouldn't make any difference in JavaScript, since the language does not have block scope, but only function scope.

I'm not sure about the performance argument, but Douglas Crockford still recommends that the var statements should be the first statements in the function body. Quoting from Code Conventions for the JavaScript Programming Language:

JavaScript does not have block scope, so defining variables in blocks can confuse programmers who are experienced with other C family languages. Define all variables at the top of the function.

I think he has a point, as you can see in the following example. Declaring the variables at the top of the function should not confuse readers into thinking that the variable i is held in the scope of the for loop block:

function myFunction() {
  var i;    // the scope of the variables is very clear

  for (i = 0; i < 10; i++) {
    // ...
  }
}
๐ŸŒ
Wes Bos
wesbos.com โ€บ for-of-es6
Quick Tip - Use let with for Loops in JavaScript - Wes Bos
August 31, 2016 - If you had an AJAX request where you are looping through a few of them, there isn't any way without an IFFE to reference what the i variable was when it ran, not what it currently is after the loop. One quick way we can fix that is if we just change var to let: for(let i = 0; i < 10; i++) { console.log(i); setTimeout(function() { console.log('The number is ' + i); },1000); }
๐ŸŒ
Medium
medium.com โ€บ better-programming โ€บ scoping-in-javascript-for-loops-c5ffac6aa92b
Scoping in JavaScript For Loops. let vs. var inside your loop | by Johannes Baum | Better Programming
4 weeks ago - I stumbled over two code snippets that made me think about the scoping in for loops and about a possible misunderstanding. The first one looks as follows: You can see it from time to time to demonstrate the event loop, the concept of closures, or as an interview question. The output of that code is: ... The variable i is captured in the closure of the anonymous function that calls console.log() and is invoked asynchronously via setTimeout().
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 69215564 โ€บ using-var-in-javascript-with-a-for-loop-issue
Using var in JavaScript with a for loop issue? - Stack Overflow
var div; var box = document.getElementById('box'); for (var i = 0; i < 5; i++) { div = document.createElement('div'); div.onClick = function() { alert('this is box # ' + i); } box.appendChild(div); } ... Because by the time you click on the ...
๐ŸŒ
Codecademy
codecademy.com โ€บ forum_questions โ€บ 50520f88b394070002002448
"var" keyword in for ... in loops | Codecademy
September 24, 2012 - Despite the name, they have no affiliation whatsoever with the W3 consortium (which defines the standards for the Web). To answer your question: all the three notations below will work, but the first is the worst one, and the last is the best one: ... This variant (no var at all) creates a gobal variable. This should be avoided. Because if somewhere else in your code (or in JavaScript libraries you use) another global variable of the same name exists, your loop variable x will overwrite its value, potentially wreaking havoc.
Top answer
1 of 3
18

let is introduced in Ecma Script 6 - the new javascript version - which is still in development at the time of this writing. Therefore, using var will get you across more browsers for the time being.

On the other hand, I urge people to use let instead of var from now on. I would go ahead and list the reasons but you have already have a link in your post with a great explanation in it. Long story short, let helps you avoid the variable hoisting in javascript and keep your variables' scope at just where it needs to be.

update

I've forgotten about this post until I recently got an upvote. I'd like to update this statement. I personally use const as much as I can these days. If you get into linting your code, which I highly recommend, and use something like airbnb lint rules, it will also tell you to use const. It will make your variables a constant so you will not be able to mutate them once you set their value thus it is not applicable in all cases. const and let also have advantages in terms of scope over var and it is well worth a read. My hierarchy of usage goes as such const > let > var

2 of 3
11

Yes, you would want to use let there as it will be scoped only to that block.

Additionally, using let in this way will let you avoid accidentally creating a closure if you are calling a function in your loop and passing the counter as a parameter.

EDIT: Maybe this should be better put as: Ask yourself if you need to access the value of your variable outside of the loop. If you do, use var; in all other cases, use let.

๐ŸŒ
Displayr
help.displayr.com โ€บ hc โ€บ en-us โ€บ articles โ€บ 360004667376-How-to-Create-JavaScript-Variables-Using-Loops-and-Arrays
How to Create JavaScript Variables Using Loops and Arrays โ€“ Displayr Help
3 weeks ago - When this option is not selected, a new JavaScript variable containing the value of 1 for each record would be created with this expression: ... The first line creates a variable called result and assigns an empty array to it. N is a reserved variable containing the number of observations in the data set. A loop is being used to iterate through all the N values.
๐ŸŒ
MDN Web Docs
developer.mozilla.org โ€บ en-US โ€บ docs โ€บ Web โ€บ JavaScript โ€บ Reference โ€บ Statements โ€บ for...of
for...of - JavaScript | MDN - MDN Web Docs
When a for...of loop iterates over an iterable, it first calls the iterable's [Symbol.iterator]() method, which returns an iterator, and then repeatedly calls the resulting iterator's next() method to produce the sequence of values to be assigned to variable. A for...of loop exits when the iterator has completed (the next() result is an object with done: true). Like other looping statements, you can use control flow statements inside statement: