-1

// x = [7,2]
let x = [7, 2];

// y = [[7,2]]
let y = [x]

// x = [9,2]
x[0] = 9;

// y also = [[9,2]]
console.log(y);

Why is it that when I changed x, y changed as well? Shouldn't y still be what it was when I initialized it [[7,2]]? What is this phenomenon called?

Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
BayCode
  • 93
  • 11

2 Answers2

1

In javascript when you copy over array to another variable, it does not copy over the data to another variable. It will create a reference to that variable, so when the original array changes, copied over array would also change this is called as call by reference.

Another term is called as call by value which will copy over the data to another variable, which is the case for primitive data types

Rakesh Jain
  • 245
  • 1
  • 9
0

Copying value by reference. - https://www.dyn-web.com/javascript/arrays/value-vs-reference.php

What you want to do instead -

let x = [7,2];

let y = [...x];

x[0] = 9;

(2) [9, 2]

y
(2) [7, 2]
Spandan
  • 221
  • 1
  • 4