Ethan Mick

Using Array: fill()

The Array Array.prototype.fill() changes all elements in an array from start to end to a static value and returns the modified array.

Syntax

fill(value)
fill(value, start)
fill(value, start, end)
// TyepScript definition
fill(value: T, start?: number, end?: number): this;

Note that this method mutates the original array!

This array method is most useful for initializing an array to n length, and then iterating over it. I use it as a more functional for loop, a syntax more useful in React. If you only use the Array(5) syntax, you wlll an array you cannot iterate over.

Examples

// Loop 5 times doing something unrelated, instead of using a `for` loop
new Array(5).fill(0).forEach(() => {
// do something
})
// Loop 5 times doing something with the index
new Array(5).fill(void 0).forEach((_, index) => {
// do something
})
// In React, map the index to an element
<>
{
new Array(5).fill(null).map((_, index) => (
<div key={index}>{index}</div>
))
}
</>

An alternative syntax for filling an array to iterate over is also:

const arr = [...Array(5)]
// which is the same as:
const arr = Array(5).fill(undefined)

If the value being used is an object it is passed by reference. If you use an object as the value it will all reference the same object, and changes will be reflected in all:

const deck = new Array(52).fill({ suit: '', value: '' })
deck[0].suit = 'Hearts'
// Unexpected!!
console.log(deck[1].suit) // 'Hearts'

This may result in some undesired behavior.

Rewriting Imperative Code to Functional

When writing functional code, fill can be used to rewrite for loops:

for (let i = 0; i < 10; i++) {
callSomeFunction()
}
// Can be changed to:
Array(10).fill(0).forEach(callSomeFunction)

Be the best web developer you can be.

A weekly email on Next.js, React, TypeScript, Tailwind CSS, and web development.

No spam. Unsubscribe any time.