Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

Array.prototype.fill

Fills an array with one value.

Available since: ES2015

Syntax

array.fill(value, start, end)

Parameters

ParameterTypeDescription
valueanyThe value to fill the array with.
startnumberOptional. The position to start from. 0 by default.
endnumberOptional. The position to stop before. To the end by default.

Return value

ArrayThe same array, filled with the value.

Examples

An array of five zeros:

console.log(new Array(5).fill(0).join(', '));

Output:

0, 0, 0, 0, 0

Filling part of an array:

console.log([1, 2, 3, 4].fill(9, 1, 3).join(', '));

Output:

1, 9, 9, 4

Notes

If you fill an array with an object or an array, every slot holds the same reference: new Array(3).fill([]) creates three references to one array. For independent values use Array.from({ length: 3 }, () => []).

See also

Related recipes

In the tutorial

  • Array methods — How to add and remove array elements in JavaScript: push, pop, shift, unshift, slice, splice, concat and join.

Thanks for reading!

Donate to the site — we work hard for you.