Search code examples
javascriptjquerybyrefgrep

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?


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