-1

Created second array = to first array and then performed 'shift' on second array and first array was affected also. See code below. I am expecting the secondArray to contain Larry and Moe after the shift and the firstArray to have the original three elements. After the shift, both arrays only have Larry and Moe as elements?

var firstArray = ["Curly", "Larry", "Moe"]
var secondArray = firstArray;
var thirdArray = firstArray;
alert("This is first array " + firstArray + "<br>");
secondArray.shift();
alert("This is first array " + firstArray + "<br>");
alert("This is second array " + secondArray + "<br>");
alert("This is third array " + thirdArray + "<br>");
  • You are not making a copy of an array - `secondArray` and `thirdArray` are references to literally _the same_ array. – VLAZ Oct 17 '16 at 17:47
  • 2
    Possible duplicate of [Copying array by value in JavaScript](http://stackoverflow.com/questions/7486085/copying-array-by-value-in-javascript) – André Dion Oct 17 '16 at 17:47

2 Answers2

0

Here secondArray & thirdArray refers to the same array as firstArray instead of a new independent array.

You can use slice which will return a shallow copy of portion of array

var firstArray = ["Curly", "Larry", "Moe"]
var secondArray = firstArray.slice();
var thirdArray = firstArray.slice();
alert("This is first array " + firstArray + "<br>");
secondArray.shift();
alert("This is first array " + firstArray + "<br>");
alert("This is second array " + secondArray + "<br>");
alert("This is third array " + thirdArray + "<br>");

DEMO

brk
  • 48,835
  • 10
  • 56
  • 78
0

Reason for this is arrays are reference types. There are tow types of variables

  1. Value types Actual value is storing in the valriable. ex - string, number, boolean, null, undefined
  2. Reference Type value will be stored in a different location(In Heap) and reference to that will be stored in the variable. objects, arrays, and functions are reference types.

    var secondArray = firstArray;

firstArray stores reference to the array which declared previously when you run above code, It copies reference of firstArray to secondArray variable. after run above line secondArray also have reference of firstArray. When you run

secondArray.shift();

it will remove first value from referred array which refer by all three variables. Please read below links for more details
Primitive value vs Reference value
http://docstore.mik.ua/orelly/webprog/jscript/ch04_04.htm

You can use slice method to get a copy of a array as below,

var secondArray = firstArray.slice();

Refere below link for some other methods

copy an array

Community
  • 1
  • 1
Nayana Priyankara
  • 1,392
  • 1
  • 18
  • 26