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?
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;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With