Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable not visible inside for loop

I have a for loop in JavaScript like

var loopvariable = 0;  
let row = [[]];
for (var key in supplies.food) {
     row[loopvariable][0] = key;
     row[loopvariable][1] = supplies.food[key];
     loopvariable++;
}

why am i getting the following error

TypeError: row[loopvariable] is undefined

like image 939
akshay kishore Avatar asked Jan 23 '26 20:01

akshay kishore


1 Answers

The variable

row[loopvariable]

is not initialized. You could use a default value and take an array with a guard operator (logical OR ||).

row[loopvariable] = row[loopvariable] || [];

A shorter approach could be just to push a new array to row, without using an aditional variable loopvariable

let row = [];
for (var key in supplies.food) {
    row.push([key, supplies.food[key]]);
}
like image 67
Nina Scholz Avatar answered Jan 26 '26 10:01

Nina Scholz