1

Please see the below code and it's corresponding output when ran on chrome console.

var x = [1,2,3,4,5,6,7,8]
var y = x;
console.log(y.length);
x.splice(1,1);
console.log(y.length);
console.log(x.length);

The output is as follows: 8 7 7

My query is since I've initialized the variable y before splicing x, then why the y is getting spliced automatically. Thanks in advance.

METALHEAD
  • 2,734
  • 3
  • 22
  • 37

3 Answers3

3

Because when you assign x to y you pass a reference of the object, so you dont copy the item. x and y are the same "object"

Constantin Guidon
  • 1,892
  • 16
  • 21
1

In JavaScript, primitive types are copied by value and reference types are copied by reference. More info here: http://docstore.mik.ua/orelly/web/jscript/ch09_03.html

Hope this helps.

hashed_name
  • 553
  • 6
  • 21
0

your code is reference to array. try this var y = [...x];

Metalik
  • 873
  • 1
  • 10
  • 28
  • I would say this does provide an answer, it's just not well explained. Try explaining why that solution would work. – Sia Jun 15 '18 at 18:10