Created
September 15, 2019 22:56
-
-
Save VinayakBagaria/6dd68ae08e435ca39f060e4003aafbe5 to your computer and use it in GitHub Desktop.
Filling an array, alternative methods
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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