I can't figure out why my function doesn't change the global variable (arrayValue) It changes it only inside the function, but I want to change it outside.
function reverseArrayInPlace(arrayValue) {
var newArr = [];
for (var i = 0; i < arrayValue.length; i++) {
newArr.unshift(arrayValue[i]);
}
arrayValue = newArr;
return arrayValue;
}
var arrayValue = [1, 2, 3, 4, 5];
reverseArrayInPlace(arrayValue);
console.log(arrayValue); // It gives [1, 2, 3, 4, 5] instead of [5, 4, 3, 2, 1]
console.log(reverseArrayInPlace(arrayValue)); // It gives [5, 4, 3, 2, 1]
Main source of confusion is that the param name of your function and your global array name got conflicted.
You are not modifying the global array, you are modifying the array which is local to that function.
You have two options now.
1) Receive the modified array
reverseArrayInPlace(arrayValue);
That function is returning modified array and you are not receiving it. Hence it is pointing to the old array.
arrayValue = reverseArrayInPlace(arrayValue);
2) Have unique naming for function param and global array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With