How to Use fill() Method in JavaScript Arrays
In JavaScript, use the
fill() method to replace all or part of an array's elements with a static value. It modifies the original array and accepts optional start and end indexes to control which elements get replaced.Syntax
The fill() method syntax is array.fill(value, start, end).
- value: The value to fill the array with.
- start (optional): The index to start filling from (default is 0).
- end (optional): The index to stop filling before (default is array length).
javascript
array.fill(value, start, end)
Example
This example shows how to fill an entire array with the number 5, and how to fill only part of an array from index 1 to 3.
javascript
const arr = [1, 2, 3, 4, 5]; // Fill entire array with 5 arr.fill(5); console.log(arr); // Output: [5, 5, 5, 5, 5] // Fill part of array from index 1 to 3 with 10 const arr2 = [1, 2, 3, 4, 5]; arr2.fill(10, 1, 4); console.log(arr2); // Output: [1, 10, 10, 10, 5]
Output
[5, 5, 5, 5, 5]
[1, 10, 10, 10, 5]
Common Pitfalls
One common mistake is expecting fill() to create a new array instead of modifying the original one. Also, the end index is exclusive, so it does not fill the element at the end position.
Another pitfall is using fill() with objects or arrays as the value, which fills all positions with references to the same object, not copies.
javascript
const arr = [1, 2, 3]; // Wrong: expecting a new array const newArr = arr.fill(0); console.log(arr); // Output: [0, 0, 0] console.log(newArr); // Output: [0, 0, 0] (same array modified) // Object reference issue const obj = {a: 1}; const arrObj = new Array(3).fill(obj); arrObj[0].a = 99; console.log(arrObj); // Output: [{a: 99}, {a: 99}, {a: 99}] because all elements reference the same object
Output
[0, 0, 0]
[0, 0, 0]
[{a: 99}, {a: 99}, {a: 99}]
Quick Reference
- fill(value): fills entire array with
value. - fill(value, start): fills from
startindex to end. - fill(value, start, end): fills from
starttoend - 1. - Modifies the original array.
- Returns the modified array.
Key Takeaways
The fill() method changes the original array by replacing elements with a static value.
You can specify start and end indexes to fill only part of the array.
The end index is exclusive and not included in the fill.
Using fill() with objects fills all positions with references to the same object.
fill() returns the modified array, not a new one.