views:

91

answers:

2

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?

+3  A: 

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);
}
Matthew Flaschen
+2  A: 

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

CMS
so what you're saying is, basically, you can change the values, but if you reassign the whole variable, the reference is lost
Jason
@Jason, exactly, the *real* value of your formal parameter is actually the reference to the object that it points to, when you make the assignment, its value will change, a new reference will be assigned to it.
CMS