Search code examples
javascriptarraysargumentsglobal-variablesscoping

eloquent javascript exercise 4.2 reversing an Array


In the following code I do not understand why reverseArrayOne does not return the reversed array as compared to reverseArrayTwo. In essence I believe I'm assigning the reversedArray to Array in both cases. link to question http://eloquentjavascript.net/04_data.html#c_F3JsLaIs+m

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

function reverseArrayOne(array) {
  array = reverseArray(array);
  return array;
}

function reverseArrayTwo(array) {
  reversedArray = reverseArray (array);
  for (i=0; i<reversedArray.length; i++) {
    array[i] = reversedArray[i];
  }
  return array;
}
var arrayValue = [1, 2, 3, 4, 5];
reverseArrayOne(arrayValue);
console.log(arrayValue);
// → [1,2,3,4,5]
reverseArrayTwo(arrayValue);
console.log(arrayValue);
// → [5, 4, 3, 2, 1]

Solution

  • Bear in mind the difference between how and object is treated different from values,variables and literals values.I've added comments explaining the procedure,bump the answer incase you need more detail.

    a major distinction is: while objects are passed by reference,the latter are passed by value

    function reverseArray(array) {
    reversedArray = [];
      for (i=array.length-1; i>=0; i--) {
        reversedArray.push(array[i]);
      }
    //return a new array with elements in a reverse order of original array
      return reversedArray;
    }
    
    function reverseArrayOne(array) {
    //scope of object reference is in the function only and hence is not reflected outside
      array = reverseArray(array);
    //return the same object pointer which now points to a new array
      return array;
    }
    
    function reverseArrayTwo(array) {
          reversedArray = reverseArray (array);
          for (i=0; i<reversedArray.length; i++) {
    //you are changing the properties of the same object(this is different from merely changing the reference of the object)
            array[i] = reversedArray[i];
          }
          return array;
        }
        var arrayValue = [1, 2, 3, 4, 5];
    //passing arrayValue as reference
        reverseArrayOne(arrayValue);
    //original arrayValue still points to the original array since the reverse value is not in scope.
        console.log(arrayValue);
        // → [1,2,3,4,5]
        reverseArrayTwo(arrayValue);
    //the original array is the same,but the internal property of the object has been changed and hence is reflected
        console.log(arrayValue);
        // → [5, 4, 3, 2, 1]