4
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?

2
  • 2
    JavaScript is a call-by-value language, so there's no way to make a function like changeArray() work. (To fend of the "but pass an object!" objections, such a solution would result in a function that's not like this one.) Commented Feb 22, 2016 at 21:34
  • You are assigning to the local array variable (the parameter), not the global one. Commented Feb 22, 2016 at 21:39

2 Answers 2

4

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;
});
Sign up to request clarification or add additional context in comments.

Comments

3

You have to call the original array by name inside the function. The original array is a global variable so you don't need to pass it as a parameter.

var array1 = [1, 2, 3, 4, 5];
console.log(array1);
changeArray();
console.log(array1);

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.