Stack Exchange
Cannot read property of undefined when accessing next element of array
I am a javascript newbie and am getting the following error on line 10 of my code:
TypeError: Cannot read property '0' of undefined
var arr = [[1,7], [2,6], [3,5], [4,4], [5,3], [6,2], [7,1]];

console.log("arr[0] = ("+arr[0][0]+","+arr[0][1]+")");
console.log("arr[1] = ("+arr[1][0]+","+arr[1][1]+")");

for (var i in arr) 
{
  console.log("i = "+i);

  if (i<arr.length - 2)
  {
    console.log(i+" ("+arr[i][0]+","+arr[i][1]+")");
    console.log(i+" ("+arr[i+1][0]+","+arr[i+1][1]+")");
  }
}

The output before this error is
arr[0] = (1,7)
arr[1] = (2,6)
i = 0
0 (1,7)

So if i=0, then i+1 is 1, and arr[1][0] is defined. As it shows above arr[1][0]=2. What is my mistake?

Don't use for...in with arrays use for...of, for...in can lead to it iterating over the non-numeric properties of the array, eg functions of the array object.

you can add console.log(typeof i) in the loop and find out that i is a string

Does this answer your question? Adding two numbers concatenates them instead of calculating the sum

If you run the below snipet, you can see that the type of i is string


var arr = [[1,7], [2,6], [3,5], [4,4], [5,3], [6,2], [7,1]];

for (var i in arr) 
{
  console.log(typeof i); // string  
}



If i is a string and i = "0", then i + 1 is not 1 but "01" instead. And arr["01"] is undefined, so you have the error.
I suggest this version, I use the old syntax


var arr = [[1,7], [2,6], [3,5], [4,4], [5,3], [6,2], [7,1]];
for (var i = 0; i < arr.length; i = i + 1) 
{
  console.log("i = "+i);

  if (i<arr.length - 2)
  {
    console.log(i+" ("+arr[i][0]+","+arr[i][1]+")");
    console.log(i+" ("+arr[i+1][0]+","+arr[i+1][1]+")");
  }
}




Thank you. I understand now.
