1

Why does this code alerts same thing (1,2,3,4) twice??

var arr = [1,2,3];
var new_arr = arr;
new_arr[new_arr.length] = 4;
alert(new_arr);
alert(arr);
Nacky
  • 31
  • 1
  • 9
  • 2
    line 2 holds the clue: `new_arr` is `arr`. – David Hedlund Apr 02 '13 at 10:18
  • 1
    The existing answers tell you why you see the behaviour you do. If you want to change the behaviour you need to copy the array and [this question](http://stackoverflow.com/questions/7486085/copying-array-by-value-in-javascript) has some useful answers. – James Allardice Apr 02 '13 at 10:18

4 Answers4

2

In JavaScript, all values are either primitive values (numbers, strings, booleans, null, undefined) or references to objects (among them the arrays, functions, etc.).

There is only one array and both variables hold references to this array.

If you want to have another array, so that you can change them independently, duplicate the first one :

var arr = [1,2,3];
var new_arr = arr.slice();
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • Thank you so much! I was writing a path-finding algorythm for one browser-based game script and that was the only promlem causing wrong answers ) I do know C# pretty well, but this is my 1st javascript program ever =) – Nacky Apr 02 '13 at 10:24
1

Because when you alter the second variable you're manipulating the underlying array, which is referenced by both variables (being representative of the thing), but it's only one thing, and which is then displayed, twice.

This is to do with reference and value types.

Grant Thomas
  • 44,454
  • 10
  • 85
  • 129
1

Arrays in JavaScript are reference object.

Hodaya Shalom
  • 4,327
  • 12
  • 57
  • 111
1

When you do this:

var arr = [1,2,3];
var new_arr = arr;

You now have two variables that are pointing at the same data structure. Assignment of arrays is by reference which means a copy of the data is not created, both variables just point to the same array.

So, no matter which variable one you modify, you will be changing the same piece of data that they both point to.

So, when you do:

new_arr[new_arr.length] = 4;

The single copy of the data has been modified and both variables will report that same change.

In javascript, if you want a copy of the data, then you have to explicitly create a copy and you also have to know whether you want to create a shallow copy (only top level items are copied) or a deep copy (even objects or arrays nested in the array are also copied).

A shallow copy is very easy for an array the the .slice() method.

var arr = [1,2,3];

// make a copy of the array
var new_arr = arr.slice(0);

// modify the copy
new_arr[new_arr.length] = 4;

alert(arr);        // shows length of 3
alert(new_arr);    // shows length of 4
jfriend00
  • 683,504
  • 96
  • 985
  • 979