0

I did:

a = Array(2).fill([]);
a[0].push(1);

Expected outcome: a = [[1], []] Got: a = [[1], [1]]

Why does the second item depend on the first one here?

Thanks in advance.

2 Answers 2

3

The call to .fill() passes a single empty array. Thus, that same array is dropped into all the elements of the filled array.

Consider that if you called Array(2).fill(3); all the elements would contain the value 3. It's really no different here.

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

Comments

1

From docs,

If the first parameter is an object, each slot in the array will reference that object.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill

Alternate using Array.from()

const a = Array.from({length: 2}, i => [])

a[0].push(1)

console.log(a)

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.