Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Working with arrays passed byref

I would like for 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;

in place of the $.grep line, i get 1,2,3,4. Shouldn't mainArray become the new array created by $.grep?

like image 266
Jason Avatar asked Nov 24 '25 14:11

Jason


2 Answers

No, the array parameter is also a local (reference) variable. The function assigns a new array to this variable, but that doesn't affect the caller's variables. All parameters (including references), are passed by value.

If you modified (mutated) the contents of array, that 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);
}
like image 60
Matthew Flaschen Avatar answered Nov 26 '25 04:11

Matthew Flaschen


It is due the evaluation stretegy that JavaScript implements.

Your function receives a copy of the reference to the object, this reference copy is associated with the formal parameter and is its value, and an assignment of a new value to the argument inside the function does not affect object outside the function (the original reference).

This kind of evaluation strategy is used by many languages, and is known as call by sharing

like image 30
Christian C. Salvadó Avatar answered Nov 26 '25 03:11

Christian C. Salvadó



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!