Skip to content

Instantly share code, notes, and snippets.

@gapurov
Created April 25, 2025 09:09
Show Gist options
  • Save gapurov/5d22f36a5fe48f479419cc2fa50caa77 to your computer and use it in GitHub Desktop.
Save gapurov/5d22f36a5fe48f479419cc2fa50caa77 to your computer and use it in GitHub Desktop.
An interesting thing to know about arrays.

What gets logged?

const array = new Array(3).fill([])
array[0].push("bytes")
console.log(array) // [ ["bytes"], ["bytes"], ["bytes"] ]

The key to understanding this one is in knowing that arrays in JavaScript are reference values. When you call .fill([]), what you’re really doing is “filling up” the array with three references to the same array. You can kind of think of it like this.

const reference = []
const array = new Array(3).fill(reference)

Where now, array has three elements and they’re all referencing the same reference array. Therefore, if you add an item to any of the three elements, since they all point to the same array, it’s as if you’re adding an item to all of them. To get the same functionality without the referential weirdness, you can use Array.from.

const array = Array.from({ length: 3 }, () => []);
array[0].push("bytes");  // [ ["bytes"], [], [] ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment