-2

Currently I am having a const current = [0,1] and push it to an array array1.push(current). Then I reassign the current to a let previous = current. If I update the previous[1] = 7, why the array1 value also updated?

qmkiwi
  • 135
  • 1
  • 5
  • 2
    Why would anything else happen? You're not making a copy, you only have one array. – jonrsharpe Aug 13 '21 at 15:23
  • `const` means that you can't reassign a different value to that variable. It doesn't mean that the object that variable is referring to becomes immutable. – Ivar Aug 13 '21 at 15:28

2 Answers2

0

previous and current are referencing same array here [0,1]. so any update you make on current or previous will reflect in the current/previous reference you pushed into the array1.

if you don’t want previous[1]=7 to change current array . then I suggest you do let previous = Array.from(current). that way current won’t change even when you run previous[1]=7 since current and previous are pointed to two different arrays( or memory spaces)

these are the keywords I look at when i get confused about this deep copy, shallow copy.

Bharat Varma
  • 154
  • 1
  • 6
-2

Just figured by myself: the = just copy the reference of original array instead of the original value.

qmkiwi
  • 135
  • 1
  • 5