techdog
techdog

Reputation: 1481

working with copies of arrays in javascript

When do variables made from arrays act as pointers to the array and when do they act as copies of the array?

For instance if I have an array named Array1

a1=Array1;     

is a1 a copy or a pointer to the array.

If I modify a1 will it also modify Array1. By modify I mean change a value, push something into the array, sort, or any other way you could modify an array.

thanks,

Upvotes: 0

Views: 65

Answers (2)

Matt Ball
Matt Ball

Reputation: 359776

Variable assignment in JavaScript never makes copies for non-primitives (everything that isn't a value).

Assignment for all non-values copies references.

Upvotes: 1

Denys Séguret
Denys Séguret

Reputation: 382102

A variable in javascript holds a reference to the array.

If you copy the variable value with arr2 = arr1, you copy the reference to the same array. So any change to arr2 is a change to arr1.

If you want another variable to hold a reference to a copy, so that you may change the second array without changing the first one, use slice :

var arr2 = arr1.slice();

Upvotes: 1

Related Questions