qua1ity qua1ity - 1 month ago 5
Javascript Question

JavaScript - Array "undefined" error

I got a problem with this simple piece of code which i cant figure out.
Instead of printing the whole array in the console, i get the message "10 undefined". Altough if i put "var i" to 0 or below then it's all good and i get a full list from that number up to 10.

Why wont this work when "i" is set to a number above 0?
Took a picture of my console in chrome to show how it looks like:

Screenshot

var ar = [];

for (var i = 1; i <= 10; i++) {
ar.push(i);
console.log(ar[i]);
}

Answer

JavaScript array indices start at 0, not 1. The .push() method adds an element at the end of the array, which in the case of an empty array (as yours is when your loop begins) will be array element 0.

Your loop inserts the value 1 at array index 0, the value 2 at array index 1, and so forth up to the value 10 at array index 9.

Each of your console.log(ar[i]) statements is trying to log a value from an index one higher than the highest element index, and those elements will always be undefined. So the console logs the value undefined ten times.

You can log the last element of an array like this:

console.log(ar[ar.length-1]);

Or in your case where you (now) know that i will be one higher than the index that .push() used:

console.log(ar[i-1]);
Comments