Array. prototype. fill()
Fills an array (or part of it) with a single value.
- Returns
- The same, filled array.
- Changes the original
- Yes
Example
#console.log(new Array(5).fill(0))
console.log([1, 2, 3, 4, 5].fill('x', 1, 3))Definition and usage
#The fill(value, start, end) method writes the given value into every element of the array, or into the section from start to end. It changes the original array and returns it.
It’s most often used to prepare an array of a known length: new Array(7).fill(0) creates seven zeros, for example as a counter for the days of the week.
Watch out with objects: fill({}) puts the exact same object into every slot, so changing one element changes all of them. To create separate objects, use Array.from({ length }, () => ({})).
Syntax
#array.fill(value)
array.fill(value, start)
array.fill(value, start, end)Parameters
#value
any value
The value to write.start
optional
The start index, 0 by default.end
optional
The end index (exclusive), defaults to the array’s length.
More examples
#const shared = new Array(2).fill({ done: false })
shared[0].done = true
console.log(shared)
const separate = Array.from({ length: 2 }, () => ({ done: false }))
separate[0].done = true
console.log(separate)Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- To fill with objects, use
Array.from()with a function so every element is its own object. fill()changes the array in place, so don’t call it on data you don’t want to modify.
Related entries
#Spotted a mistake or missing an example? Write to us.