0

after I run below codes why myArray is still [2, 3, 4, 5], why it is not changed to []?

var myArray = [2, 3, 4, 5];
function doStuff(arr) {
  arr = [];
}

doStuff(myArray);

However when I do below steps , myArray did change to [2, 3, 4, 5, 6]

var myArray = [2, 3, 4, 5];
function doStuff(arr) {
  arr.push(6);
}

doStuff(myArray);

I am very confusing about this.

2 Answers 2

2

arr is a local variable in

function doStuff(arr) {
  arr = [];
}

The line arr = []; assigns a brand new object to arr, so that it no longer points to the passed array. Since the local variable arr goes out of scope when the function returns, this assignment has no effect. It certainly doesn't effect the non-local variable myArray in the caller's scope.

On the other hand, the second function:

function doStuff(arr) {
  arr.push(6);
}

actually does something with the passed array, calling the push method on the object that arr names. Note that arr isn't redefined in the body of the function, so that it never loses its identity as a name for the passed array.

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

Comments

0

What you did is okey if you don't have references to the myArray because this actually creates an empty array. If you have references to myArray from another variable in somewhere of your code, you coudn't set as null you did. As an alternative, you can use following method to clear. Otherwise, if it is not important, you can remove references.

while(myArray.length > 0) {
    myArray.pop();
}

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.