Search code examples
javascriptarraysundefined

First element of array undefined after push in JavaScript


If I declare an array and then push to it, it will have length "2" not "1", and the first element will be undefined.

let myArray = [new Array(2)];
myArray.push(['hi', 'hello']);
alert(myArray[0][0]);

This will be undefined:

enter image description here

However, if I change it to alert(myArray[1][0]); it will display what should be the first element of the array.

Why?


Solution

  • Given this:

    let myArray = [new Array(2)];
    myArray.push(['hi', 'hello']);
    

    The question is why does the following output undefined:

    alert(myArray[0][0]);
    

    Answer:

    new Array(2) creates an array with two elements and both elements are set to the value of undefined.

    let myArray = []; creates a new empty array.

    let myArray = [new Array(2)]; creates an array that contains one element. That one element is an array containing two elements whose value is undefined.

    myArray.push(['hi', 'hello']); adds one element to the end of myArray. This one element is an array containing two elements, 'hi' and 'hello'.

    At this point, myArray looks like this:

    let myArray = [
        [undefined, undefined],
        ['hi, 'hello'],
    ];
    

    So if you go to myArray[0] you get the first element, which is an array, then you go to the first element of that array, which is undefined.

    That is why alert(myArray[0][0]); outputs undefined.