Working with arrays passed by byref
I would like someone to explain this to me:
function myFunction(array){
array = $.grep(array, function(n,i){return n > 1 });
}
var mainArray = [1,2,3];
myFunction(mainArray);
document.write(mainArray) // 1,2,3, but i'm expecting 2,3
but if i do something like
array[3] = 4;
instead of a string $.grep
, I get 1,2,3,4
. Shouldn't it mainArray
become a new array created $.grep
?
a source to share
No, the parameter is array
also a local (reference) variable. The function assigns a new array to this variable, but this does not affect the caller variables. All parameters (including links) are passed by value.
If you changed (changed) the content array
, it would be different:
function myFunction(array){
var grepResult = $.grep(array, function(n,i){return n > 1 });
array.length = 0;
Array.prototype.push.apply(array, grepResult);
}
a source to share
This is due to the stretegy score that JavaScript implements.
Your function receives a copy of the object reference, this reference copy is associated with the formal parameter and is its value, and assigning a new value to an argument inside the function does not affect the object outside the function (original reference).
This evaluation strategy is used in many languages ββand is known as challenge by sharing
a source to share