Trung Nguyen
Trung Nguyen

Reputation: 868

Does Javascript pass array to function by reference or value?

As my understand, Javascript pass object by reference, and a array also a object but when I create a array of integer then passing it to a function as below code:

function testFunc(outTestArray) {
  var aiTemp = [1,2,3,4];

  /*Using slice(0) to clone array */
  outTestArray = aiTemp.slice(0);
}

var aiTest = Array.apply(null, Array(4)).map(Number.prototype.valueOf, 0);
testFunc(aiTest);

console.log(aiTest.toString()); // aiTest still [0,0,0,0]

I also know that the slice(0) function just return a shallow copy of array, but in case the array is only a array of integer. So my question is why the data of aiTest is not modified?

Upvotes: 8

Views: 12722

Answers (3)

Ziarno
Ziarno

Reputation: 7562

Function arguments are like new variable assignments, it's not like references or pointers in C. It's more something like this:

function testFunc(...args) {
  var outTestArray = args[0];
  var aiTemp = [1,2,3,4];

  /*Using slice(0) to clone array */
  outTestArray = aiTemp.slice(0);
}
...

As you can see, in the code above you are cloning the array and assigning it the variable outTestArray scoped within the function, which is not accessible outside of it.

You could use a closure to achieve what you want:

var outerArray;
function testFunc(array) {
  var aiTemp = [1,2,3,4];
  outerArray= aiTemp.slice(0);
}

or even better, just return a new array:

function getArray() {
  return [1,2,3,4];
}

var aiTest = getArray();
...

Upvotes: 1

Sameer Jalnapurkar
Sameer Jalnapurkar

Reputation: 1

In your code, testFunc gets a reference to the original array which is copied into argument outTestArray. In the body of the function you are making outTestArray point to a different array. If you want to change the original array, then you could say

outTestArray.splice(0, outTestArray.length, ...aiTemp)

Note that spread operator is being used for aiTemp.

Upvotes: 0

Chris Kitching
Chris Kitching

Reputation: 2655

Your error is that your concept of a shallow copy is wrong.

A shallow copy copies the contents of the array, but does not copy the things referred to by array members.

If your array was an array of references to objects, a shallow copy would copy the references, so your new array would point to the same underlying objects.

But this array is ints. The ints themselves get copied by a shallow copy.

Upvotes: 0

Related Questions