Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning new value to an existing array (global var) within a function doesn't work. Why?

var array1 = [1, 2, 3, 4, 5];

// function 1 below which assigns a whole new value to an array, doesn't work

function changeArray(array) {
  array = ["A", "B", "C"];
};

// function 2, which simply modifies one element within an array, does work

function addArray(array) {
  array.push(6);
}

**// If I run function one (changeArray) on array1 and then try to print array1, it remains unchanged. However, running function 2 (addArray) does indeed add another element "6" into the array. What am I missing?

like image 599
Serge Avatar asked Mar 14 '23 05:03

Serge


1 Answers

You're assigning a new value to the contextual namespace location identified as "array". You should think of the call as:

function changeArray() {
    var thisNamespace = {}; // Not a real variable
    thisNamespace["array"] = arguments[0];
    // ...
    thisNamespace["array"] = ["A", "B", "C"];
}

I'd hope that it's clear that this doesn't replace the original argument but you can still modify the array because that's not an assignment. If you actually want to do assignment via a function you should either use its return value or a closure.

function foo(bar) {
    return ["A", "B"];
}
var x = ["C"];
x = foo(x);

Or:

function foo(baz) {
    baz(["A", "B"]);
}
var x = ["C"];
foo(function(bar) {
    x = bar;
});
like image 200
Jim Driscoll Avatar answered Mar 15 '23 23:03

Jim Driscoll