Search code examples
javascriptarraysreversing

new to javascript, working with arrays


Wondering why i needed to add 4 to the array length in order for it to print out the entire array in reverse?

before i added 4 it was just using the .length property and it was only printing out 6543.

thanks in advance!

function reverseArray(array) {
    var newArray =[];

     for(var i = 0; i <= array.length+4; i++) {
         newArray += array.pop(i);
      }
     return newArray;
 }
var numbers = [1,2,3,4,5,6];
console.log(reverseArray(numbers));

Solution

  • In Javascript, pop always removes the last element of the array. This shortens length, meaning that i and array.length were converging.

    You can do a few things to avoid this behavior:

    1. Store the original length when you start the loop: for (var i = 0 , l = array.length; i < l; i++)
    2. Copy over values without modifying the original array