I have a Javascript function called reverseArray that takes an array as the argument and returns a new array which has the same values as the input array in reverse order. I want to create a function called reverseArryInPlace which would change the value of the input array to the reverse order.
function reverseArray(inputArray) {
var outputArray = [];
for (var i = inputArray.length - 1; i >= 0; i--)
outputArray.push(inputArray[i]);
return outputArray;
}
function reverseArrayInPlace(inPlaceInputArray) {
inPlaceInputArray = reverseArray(inPlaceInputArray);
console.log('Inside reverseArrayInPlace: ' + inPlaceInputArray);
return inPlaceInputArray;
}
var arrayValue = [1, 2, 3, 4, 5];
reverseArrayInPlace(arrayValue);
console.log('Outside reverseArrayInPlace: ' + arrayValue);
// Expected Value: [5, 4, 3, 2, 1]
Here is the result I get when I execute this chunk of code:
Inside reverseArrayInPlace: 5,4,3,2,1
Outside reverseArrayInPlace: 1,2,3,4,5
Within the reverseArrayInPlace function the arrayValue variable has been reversed as expected. Why is it that when I reference the same variable outside the reverseArrayInPlace function, it is back to the original order?