Search code examples
javascriptfor-loopreferenceerror

Javascript: Basic for loop is not working


Is there any reason why the following would not work:

for (i=0;i < someArray.length;i++) {
    if (someArray[i].indexOf("something") !== -1) {
        //do something here
    }
}

The most basic "for" loop possible. But it doesn't work. On the first line (declaration of the loop, not inside the loop), I get "Uncaught reference error; i is not defined."

I have this page open in one Chrome tab, and another earlier version of the page open in another tab. In the other tab, this loop works just fine; in the first tab, this code throws an error.

EDIT - July 2 2015

The response about strict mode was helpful. After reading up a bit and going through the code I've got a handle on what's going on.

The confusing bit was that both versions of the code look like this, with some minor differences (requirejs module):

define(
    'viewModels/someViewModel',
    ['dependency1', 'dependency2', 'dependency3'],
    function(dep1, dep2, dep3) {

        "use strict";

        function SomeViewModel(arg1, arg2) {
            var self = this;
            self.initialize();

            self.removeRefinement = function(refinementString) {
                var refinementArray = refinementString.split("&");

                for (i=0;i < navigationArray.length;i++) { //<-- error

                }
            }
        }
    }
);

One version throws the reference error. One doesn't.

This is a large web application with many other pages and Javascript files. The only thing I could think of was that in one version of the code, maybe i had been inadvertently globally defined somewhere else in the app, where strict mode wasn't enabled. After running to the breakpoint and checking "window" I see that's exactly what's happening.

Thanks =D


Solution

  • If you are in strict mode, you'll get the error Uncaught reference error; i is not defined. If you're not in strict mode, you won't get the error.

    This will throw the error

    'use strict'
    var someArray = ['aaa', 'bbb', 'ccc'];
    
    for (i=0;i < someArray.length;i++) {
      console.log(i)
      if (someArray[i].indexOf("something") !== -1) {
        //do something here
      }
    }

    This won't

    var someArray = ['aaa', 'bbb', 'ccc'];
    
    for (i=0;i < someArray.length;i++) {
      console.log(i)
      if (someArray[i].indexOf("something") !== -1) {
        //do something here
      }
    }