Nacky
Nacky

Reputation: 31

A strange thing with js variables

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);

Upvotes: 1

Views: 87

Answers (4)

jfriend00
jfriend00

Reputation: 707526

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

Upvotes: 1

Hodaya Shalom
Hodaya Shalom

Reputation: 4417

Arrays in JavaScript are reference object.

Upvotes: 1

Denys Séguret
Denys Séguret

Reputation: 382167

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();

Upvotes: 2

Grant Thomas
Grant Thomas

Reputation: 45083

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.

Upvotes: 1

Related Questions