javascript reverse an array without using reverse() Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of javascript reverse an array without using reverse() without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I want to reverse an array without using reverse() function like this:

function reverse(array){
    var output = [];
    for (var i = 0; i<= array.length; i++){
        output.push(array.pop());
    }

    return output;
}

console.log(reverse([1,2,3,4,5,6,7]));

However, the it shows [7, 6, 5, 4] Can someone tell me, why my reverse function is wrong? Thanks in advance!

Answer

array.pop() removes the popped element from the array, reducing its size by one. Once you’re at i === 4, your break condition no longer evaluates to true and the loop ends.


One possible solution:

function reverse(array) {
  var output = [];
  while (array.length) {
    output.push(array.pop());
  }

  return output;
}

console.log(reverse([1, 2, 3, 4, 5, 6, 7]));
We are here to answer your question about javascript reverse an array without using reverse() - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji