Search code examples
javascriptjshint

JSHint: "Unexpected 'var'" in For Loop


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! :)


Solution

  • 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
        }
    };