is there a way to change the original reference to an object in a function call

I did some googling and, through some old posts, discovered that the array was being passed by value to the function, that is, the array variable, which pointed to an array object, was being passed by value, and changing that copy did not affect the original variable that was pointing to my array object.

Exactly right.

Is there a way to change the original reference to an object in a function call

No, JavaScript is still a purely pass-by-value language. While I suppose it’s possible for that to change at some point, it hasn’t as of this writing (and it seems really unlikely to me it ever will). If you do example(x) when x contains 42 (or an array reference), there still isn’t any way for example to reach out and change the value of x (to 43, or to refer to a different array). If x refers to a mutable object (like an array), example can modify that object, but it can’t make x refer to a whole new object.

Your workaround works by modifying the existing array. FWIW, in general it would be preferred to return the new array instead, so the caller has the option of either keeping the original or using the new one. E.g.:

function removeFromList(array, arrayName, key) {
    array = array.filter(function(element) { return element.key !== key; });
    localStorage.setItem(arrayName, JSON.stringify(array));
    return array;
}

And then when using it:

variableContainingArray = removeFromList(variableContainingArray, "nameInLocalStorage", 42);

But if you want to update in place, you don’t need a temporary array:

function removeFromList(array, arrayName, key) {
    // Looping backward we don't have to worry about the indexes when we remove an entry
    for (let i = array.length - 1; i >= 0; --i) {
        if (array[i].key === key) {
            array.splice(i, 1);
        }
    }
    localStorage.setItem(arrayName, JSON.stringify(array));
}

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top