-1

How come with this

var prodataTemp = [];
prodataTemp = prodata;  
prodataTemp.shift();

both variable prodatTemp and prodata are shifted? I can see it in the console.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
Louis
  • 2,548
  • 10
  • 63
  • 120
  • possible duplicate of [Is JavaScript a pass-by-reference or pass-by-value language?](http://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language) – Qantas 94 Heavy Oct 19 '14 at 10:31

1 Answers1

1

Assigning a JavaScript object to another variable, will not copy the contents, but it make the left hand side variable, a reference to the right hand side expression. So,

var prodataTemp = [];

made prodataTemp refer an empty array and then

prodataTemp = prodata;

makes prodataTemp refer the same array object prodata was pointing to. (So, the old empty array is no more referenced by prodataTemp).

To actually make a copy**, use Array.prototype.slice, like this

prodataTemp = prodata.slice();

Now, prodataTemp refers to the copy of the array prodata, so that shifting one will not affect the other.


** - The copy made is just a shallow copy. So, if you have an array of arrays, then a new array will be created with all the references to the elements of the old array. So, mutating one array element will have its impact in the other as well.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497