2

I would not expect foo to change at all in this example, but when I modify it as an array in the function, it changes the argument. Notice foo is not changed by function1...I guess because it doesn't modify the argument directly??? Any help avoiding this would be greatly appreciated.

http://jsfiddle.net/t47kD/

var foo = [1,2,3];

bar = function1(foo);
bar = function2(foo);
bar = function3(foo);


function function1(newFoo){
    newFoo = [newFoo,'a',1];
    return newFoo;
} //foo after function1 = 1,2,3


function function2(newFoo){
    newFoo[0] = 'a';
    return newFoo;
} //foo after function2 = a,2,3


function function3(newFoo){
    newFoo.push('4');
    return newFoo;
} //foo after function3 = a,2,3,4
Jacob Mattison
  • 50,258
  • 9
  • 107
  • 126
Geoffrey Burdett
  • 1,906
  • 1
  • 14
  • 26

4 Answers4

1
var foo = [1,2,3];

bar = function1(foo);
bar = function2(foo);
bar = function3(foo);


function function1(newFoo){
    return [newFoo,'a',1];
} //foo after function1 = 1,2,3


function function2(newFoo){
    var otherFoo = newFoo.slice(0);

    otherFoo[0] = 'a';
    return otherFoo;
} //foo after function2 = 1,2,3


function function3(newFoo){
    var otherFoo = newFoo.slice(0);

    otherFoo.push('4');
    return otherFoo;
} //foo after function2 = 1,2,3
ItsCosmo
  • 811
  • 7
  • 7
1

In function2 and function3, you're modifying the input variable (by changing its contents).

In function1, you're not modifying the input variable; you're merely assigning it to point to something else with =.

Objects (including arrays) are passed by reference - if you don't want to modify the input, the safest thing to do is make a copy of the input at the beginning of the function (before potentially modifying it). For arrays, you can do this with the slice function: var copy = input.slice(0)

Krease
  • 15,805
  • 8
  • 54
  • 86
1

Objects, including arrays are assigned by reference in ECMAScript. So, when you modify the array in the function you are modifying the same array as you passed into the function, not a new copy of the array.

A quick way to perform a shallow copy of an array is using slice(0) (and in some modern engines you can leave out the 0). See this answer about copying an array.

Also see this answer for some examples.

Community
  • 1
  • 1
Paul
  • 139,544
  • 27
  • 275
  • 264
0

When you pass an array to a function, it passes by reference. In both function2 and function3, you're modifying the foo array. In function1, newFoo would consist of an array with the first item being foo, then the values a and 1.

GeekSharp
  • 93
  • 2
  • 10