-4

I am running JSHint on my Javascript code to try and clean it up and it is giving me this warning:

 #3 Unexpected 'var'.
    for (var i = 0; i < self.myArray.length; i++) { // Line 88, Pos 14

Expanding this out, it is this piece of code:

self.myFunction = function() {
    for (var i = 0; i < self.myArray.length; i++) {
        // Do some stuff
    }
};

I have searched the internet and seen many ways to write a for loop. Some use var, some don't, others use let etc.

I can't seem to find any info on how JSHint expects me to construct my for loop. Can anyone enlighten me on some best practice, or what JSHint is looking for?

Thanks! :)

Finn LeSueur
  • 479
  • 5
  • 18
  • 2
    Does this answer your question? [Why does not JSLint allow "var" in a for loop?](https://stackoverflow.com/questions/23105006/why-does-not-jslint-allow-var-in-a-for-loop) – ASDFGerte Jan 22 '20 at 03:39
  • Yes, this answers it! Writing my loop like this fixes the scoping issue and the JSHint error (I think): ``` self.myFunction = function() { var i; for (i = 0; i < self.myArray.length; i++) { // Do some stuff } }; ``` – Finn LeSueur Jan 22 '20 at 20:04

1 Answers1

1

If you use var then it will create the variable as the enclosed function scoped or global scope (if not inside a function).

So always use let in for loop, the scope will be only within for loop.

self.myFunction = function() {
    for (let i = 0; i < self.myArray.length; i++) {
        // Do some stuff
    }
};
Sohail Ashraf
  • 10,078
  • 2
  • 26
  • 42