Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 411
Trung Nguyen Avatar asked Mar 05 '16 04:03

Trung Nguyen


1 Answers

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();
...
like image 184
Ziarno Avatar answered Nov 15 '22 12:11

Ziarno