Skip to content

Instantly share code, notes, and snippets.

@t-eckert
Created May 21, 2023 02:47
Show Gist options
  • Save t-eckert/63ac6c886d833974226216abef0c68eb to your computer and use it in GitHub Desktop.
Save t-eckert/63ac6c886d833974226216abef0c68eb to your computer and use it in GitHub Desktop.
Unpacking Array Weirdness for Andrew
/* # Unpacking array weirdness
*
* I recreated the problem you were seeing with your JavaScript.
* The root cause of the issue is `gridline` is a reference to an array.
* It is that reference that is being copied into the `gameGridArray`.
*
* Let's walk through the offending code step-by-step and see what's happening.
*/
let gridline = new Array(4).fill(0); // The `gridline` object is being initialized with 4 zeros.
// If we were to `console.log` the `gridline` object, we would see `[0, 0, 0, 0]`.
console.log(gridline);
// Now we are creating a new array, `gameGridArray`, and filling it with 4 copies of the `gridline` object.
// Note that we are not copying the contents of the `gridline` object, but the reference to the `gridline` object.
let gameGridArray = new Array(4).fill(gridline);
// So if you were to print this out to the console, you would see `[[0, 0, 0, 0], [0, 0, 0, 0], ...]`.
console.log(gameGridArray);
// However, we can think of the `gameGridArray` as being initialized like this:
// `[gridline, gridline, gridline, gridline]`.
// In the next line, where you are setting the value of `gameGridArray[2][2]` to `4`,
// you are actually editing the value of `gridline[2]` to `4`.
gameGridArray[2][2] = 4;
// The above line is equivalent to `gridline[2] = 4`.
// Because the `gameGridArray` is just an array of references to the `gridline` object,
// when you change that value, you change it in all of the locations where it is referenced.
//
// That is why you get the output of `[[0, 0, 4, 0], [0, 0, 4, 0], ...]`.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment