Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"assignment to undeclared variable" when using "for (i=0; ..)"

Tags:

javascript

Hey I'm trying to get list of all input fields in a HTML form, but I get following error(in Firebug):

ReferenceError: assignment to undeclared variable i
for (i=0 ; i<inputs.length; i++)

I don't understant how is "i" undeclared because that is that first part of "for" does. This is my formula

 function listinputs() 
    {
       var form = document.getElementById("wholeform");
       var inputs = form.childNodes;
       for (i=0 ; i<inputs.length; i++)
       {
          var string=string + inputs[i].nodeName + "<br>";
          var here = document.getElementsByTagName("p");
          here.innerHTML(string);
       }
}
like image 313
sgp667 Avatar asked Apr 03 '14 22:04

sgp667


2 Answers

for (var i=0; i<inputs.length; i++)

You need to declare it with var

As T.J said in his answer, since you're using strict mode, an implicit global is not made. That's why an error is thrown.

like image 148
Sterling Archer Avatar answered Oct 16 '22 13:10

Sterling Archer


It's not saying i is unassigned, it's saying it's undeclared. The code never declares an i variable, but then tries to assign a value to it (in the initialization part of the for loop). Apparently you're using strict mode (good!), and so the engine is giving you an error rather than creating an implicit global.

Declare i using var in the function, e.g.:

function listinputs() 
{
    var form = document.getElementById("wholeform");
    var inputs = form.childNodes;
    var i; // <=================================== Here
    for (i=0 ; i<inputs.length; i++)
    {
        string=string + inputs[i].nodeName + "<br>";
        here = document.getElementsByTagName("p");
        here.innerHTML(string);
    }
}

Side note: In ES6, when it arrives, if you want you can use let and scope i to the for statement only. But for now, use var.

like image 16
T.J. Crowder Avatar answered Oct 16 '22 14:10

T.J. Crowder