undefinded value added to array

Viewed 50

I have coded a array reverse function

which should returns like the standard reverse() method a new reversed array.

function reverseArray(array){

    let new_array = [];
    for (let i = array[array.length-1]; i >= 0; i --) {

        new_array.push(array[i]);
        console.log(typeof new_array[i]);
    }
    return new_array;
}

the output differs from the expected outcome

let my_array = [1,2,3,4,5];
console.log(reverseArray(my_array));
// -> [ undefined, 5, 4, 3, 2, 1 ]

the first inserted value is of type undefined which I can not understand why

the outcome of console.log(typeof new_array[i]); to trace what type the inserted values have gave me

undefined
undefined
undefined
number
number
undefined

which confuses me even more

1 Answers

You need the length of the array, not the last element.

for (let i = array.length - 1; i >= 0; i--) {

For getting the type of the item, you need to take the last index, not the index of the original array. For example at beginn, you have i = 4, but in the reversed array, the value at this index is undefined, because the length is one. And so on.

function reverseArray(array) {
    let new_array = [];
    for (let i = array.length - 1; i >= 0; i--) {
        new_array.push(array[i]);
    }
    return new_array;
}

let my_array = [1, 2, 3, 4, 5];

console.log(reverseArray(my_array));

Related