sgp667
sgp667

Reputation: 1875

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

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

Upvotes: 13

Views: 24792

Answers (3)

Sankar_k
Sankar_k

Reputation: 111

ERROR Message

ReferenceError: assignment to undeclared variable "x" (Firefox)
ReferenceError: "x" is not defined (Chrome)
ReferenceError: Variable undefined in strict mode (Edge)

Invalid cases
In this case, the variable "bar" is an undeclared variable.

function foo() { 
  'use strict'; 
  bar = true; 
} 
foo(); // ReferenceError: assignment to undeclared variable bar

Valid cases
To make "bar" a declared variable, you can add the var keyword in front of it.

function foo() {
  'use strict';
  var bar = true;
}
foo();

Upvotes: 0

Sterling Archer
Sterling Archer

Reputation: 22405

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.

Upvotes: 29

T.J. Crowder
T.J. Crowder

Reputation: 1075129

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.

Upvotes: 16

Related Questions