Skip to content

Instantly share code, notes, and snippets.

@VinayakBagaria
Created September 15, 2019 22:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save VinayakBagaria/6dd68ae08e435ca39f060e4003aafbe5 to your computer and use it in GitHub Desktop.
Save VinayakBagaria/6dd68ae08e435ca39f060e4003aafbe5 to your computer and use it in GitHub Desktop.
Filling an array, alternative methods
const length = 3;
const resultA = Array.from({ length }, () => ({}));
const resultB = Array(length).fill({});
resultA; // => [{}, {}, {}]
resultB; // => [{}, {}, {}]
resultA[0] === resultA[1]; // => false
resultB[0] === resultB[1]; // => true
/*
Happens in the 1st case bcoz, 2nd arg to Array.from() is a map function:
initialized with different instances of empty objects bcoz a new func is created
Array.fill() initializes with the same instance of an empty object.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment