Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't change global variable inside a function (Javascript)

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]
like image 442
Tgralak Avatar asked Mar 15 '26 21:03

Tgralak


1 Answers

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.

like image 50
Suresh Atta Avatar answered Mar 17 '26 10:03

Suresh Atta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!