0

could someone please explain, why the Code behaves this way? I wrote a test function to illustrate the issue I have on a greater scale in my code. I want "b" to keep the value [1, 2, 3] and then update "a" to [2, 2, 3] using the math.random function. But both get updated and I don't understand why. How can I save the value [1, 2, 3] in b without beingt updated?

let a = [1, 2, 3]
let b = []

function assignB() {
    b = a
}

function reassignA() {
    console.log(b)  // [1, 2, 3]
    let randomNumber = Math.floor(Math.random() * a.length)
    if (a[randomNumber] == 1) {
        a[randomNumber] = 2
        console.log(b) // [2, 2, 3]
    } else {
        reassignA()
        }
    console.log(b) // [2, 2, 3]
}

function test() {
    assignB()
    reassignA()
}

test()
  • a and b has the same array reference here. Assign array as 'b = [...a]' should solve the problem. – vbrin27 Aug 02 '20 at 11:34

1 Answers1

0

When you write b = a you point this same object - array. Because you change this object, it does not matter if you use a or b to point this object. What you want to do is clone array, you can just write

let b = JSON.parse(JSON.stringify(a));

but there are many ways to do that

Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
woda
  • 107
  • 1
  • 5
  • https://medium.com/@naveenkarippai/learning-how-references-work-in-javascript-a066a4e15600 this article will explain this better – woda Aug 02 '20 at 11:21