JavaScript - Array "undefined" error

45,499

Solution 1

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

Solution 2

"10 undefined" means that the console showed "undefined" 10 times.

As thefourtheye says in his comment, you're pushing the value i but the index of the element that you just pushed onto the end of the array is i - 1. This means that each time you console.log(ar[i]) you're logging something that's not yet defined.

This is all because the first element in the array is ar[0], not ar[1]. You can fix your problem by logging like so: console.log(ar[ i - 1 ]);

Share:
45,499
qua1ity
Author by

qua1ity

Updated on October 18, 2020

Comments

  • qua1ity
    qua1ity over 3 years

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