Question

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?

Was it helpful?

Solution

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);
}

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top