Today I learned about Array.prototype.fill
and friends.
You can use the method to fill an array with values, or create a new array filled with values.
Pitfall: if you fill a new array with a value that is an object, each slot in the array will reference that object.
const newArr = Array(4).fill([]) > [[], [], [], []]
newArr[1].push(8) > 1
newArr > [[8], [8], [8], [8]]
Further Reading
- MDN:
Array.prototype.fill
- ECMAScript 6’s new array methods by Dr. Axel Rauschmeyer