Robert Lock Robert Lock - 2 years ago 88
Javascript Question

Why this reverse function isn't working?

Why isn't this working?
ps. I don't want to use any other variable to make it work, and i don't want to use built in functions, just asking why THIS is not working?

function reverse(arr){
for(var i =0; i< arr.length; i++){
return arr;

Answer Source

There are a lot of flaws in your code.

  • When you start pushing arr.push(arr[arr.length-i]); the array length increases, thereby, you won't get a consistency in the data.
  • This goes inside an infinite loop, as every time, the arr is ahead of its length.

It is better to use another variable and reverse, or you can use the built-in reverse() function. There's nothing wrong in having another variable and add temporary contents in it.


Using a temporary array:

function reverse(arr) {
    var final = [];
    for (var i = arr.length - 1; i >= 0; i--) {
    return final;

Using built-in function (Array.prototype.reverse()):

function reverse(arr) {
    return arr.reverse();

Using few temporary variables:

a = [5,4,3,2,1];
function reverse(arr) {
  var i = 0, j = arr.length - 1;
  for (i = 0; i < j; i++, j--) {
    var temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
  return arr;


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download