3

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]

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

Comments

2

The main problem in your question...

why my function doesn't change the global variable?

... is that you're mistaking the parameter in your function (named arrayValue) with your global (also named arrayValue).

You can easily see this if you give your function another parameter:

function reverseArrayInPlace(arrValue) {
  var newArr = [];
  for (var i = 0; i < arrValue.length; i++) {
    newArr.unshift(arrValue[i]);
  }
  arrayValue = newArr;
}

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

reverseArrayInPlace(arrayValue);

console.log(arrayValue);

Note that in this snippet the function is not returning anything (actually it's returning undefined), just changing your global.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.