0

so I just came across this, but could anyone explain it to me, why is this phenomenon present here? I didn't find any help online...

1.So if I were to get the following two arrays:

let a = [];
let b = ['','',''];

2.and then push array b into array a three times:

a.push(b);
a.push(b);
a.push(b);

3.but then when I try to change the first element of the first array like so:

a[0][0] = 'foo';

4.then all the first element of ALL the arrays change, not just the first one, as console.log(a) outputs:

(3) [Array(3), Array(3), Array(3)]
0: Array(3)
  0: "foo"
  1: ""
  2: ""

1: Array(3)
  0: "foo"
  1: ""
  2: ""

2: Array(3)
  0: "foo"
  1: ""
  2: ""

I would like to ask, why does this happen and in what way could I change an element based on its index inside of array a

1
  • The indices in a are all holding a reference to b -- "they all get updated" is a bit misleading, you're updating one object and it appears in multiple places. Commented Dec 6, 2020 at 4:53

3 Answers 3

2

b is a pointer to a mutable array, changing the array it points to will cause the other places you point to it to update as well.

You would either push copies of b into the array or create a modified copy of b when trying to mutate the value it points to.

Sign up to request clarification or add additional context in comments.

Comments

1

Because you're passing b which is just a reference to an object. To have the behavior you want, change your code to be like this:

a.push(b.map((x) => x))

For more see this page.

Comments

1

if you console.log(b), you'll see that as well.
Try doing b[1] = "test" then check the value of a and you'll see all the b's that were pushed into there have test in them too.
b is a reference so anytime you change the value of it, you are altering the places it is referenced to.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.