Search code examples
javascriptarraysarray-reverse

Reversing an Array in Place why does it not work?


function reverseArray(array) {
    var reversed_array = [];
    for(var i = 0; i < array.length; i++) {
        reversed_array.unshift(array[i]);
    }

    return reversed_array;
}

function reverseArrayInPlace(array) {
    console.log(array); //[1,2,3,4,5] 

    array = reverseArray(array);
    console.log(arguments); //{0: [5, 4, 3, 2, 1]} this is good.
    console.log(array);    // [5, 4, 3, 2, 1] this is also good.
    return array;         //should return [5, 4, 3, 2, 1]   
}

console.log(reverseArray(["A", "B", "C"]));   //["C", "B", "A"]


var arrayValue = [1, 2, 3, 4, 5];
reverseArrayInPlace(arrayValue);

console.log(arrayValue);  // [1, 2, 3, 4, 5] *wrong*

here is the problem I want to override the variable (arrayValue) with the return value of reverseArrayInPlace() just like array.reverse() does.

and here is a solution for the problem

function reverseArrayInPlace(array) {

  var half = Math.floor(array.length / 2);

  for(var i = 0; i < half; i++) {
    var current = array[i];
    array[i] = array[array.length - 1 - i];
    array[array.length - 1 - i] = current;
  }

  console.log(array);    // [5, 4, 3, 2, 1] this is good.
  return array;         //should return [5, 4, 3, 2, 1]
}

var arrayValue = [1, 2, 3, 4, 5];
reverseArrayInPlace(arrayValue);

console.log(arrayValue);  // [5, 4, 3, 2, 1]   *it works!*

I don't understand why this solution works in replacing (arrayValue) with the new value, if both reverseArrayInPlace() functions have a return statement with the same value.

Can someone please explain I'm fairly new to programming, thanks!


Solution

  • The problem with your first code example is this: When you call reverseArrayInPlace(arrayValue); you are not assigning the result of that function call to arrayValue, so arrayValue doesn't change.

    arrayValue = reverseArrayInPlace(arrayValue);
    

    would solve that.

    Now for why the reverseArrayInPlace function in your first example doesn't change the actual array elements, but the second example does:

    When you pass an array as a variable to a function it is passed by reference, not by value, so you are essentially passing a pointer (array) to the function, which it is going to work with to access the actual content of the array. This reference only exists inside the scope of the function, so changing it does not affect the actual array.

    array = reverseArray(array);
    

    Here you are changing exactly this reference, but this change only applies inside the reverseArrayInPlace function and hence does not change your actual array. In your second example, however you are accessing the original array directly and changing its elements. This is why your second example works, and your first one doesn't.