Course contentsShow
← JavaScript
Lesson 820 of 2,72319. ArraysFree lesson

fill(): Replacing Elements with a Static Value

Fill all or part of an array with a static value using fill().

fill(): Replacing Elements with a Static Value

What you'll learn: How to quickly overwrite all or part of an array with the same repeated value using fill().

What fill() Does

The fill() method replaces elements in an array with a single static value. It's like painting over a section of your array with the same color—every element in the target range gets the exact same value. This method mutates the original array and returns a reference to it.

Basic Syntax

array.fill(value)
array.fill(value, startIndex)
array.fill(value, startIndex, endIndex)
  • value: The value to fill with (can be any type)
  • startIndex (optional): Where to start filling (default: 0)
  • endIndex (optional): Where to stop filling, not including this index (default: array.length)

Examples

const nums = [1, 2, 3, 4, 5];
nums.fill(0);
console.log(nums); // [0, 0, 0, 0, 0]

const colors = ['red', 'blue', 'green', 'yellow'];
colors.fill('orange', 1, 3);
console.log(colors); // ['red', 'orange', 'orange', 'yellow']

const scores = [10, 20, 30, 40];
scores.fill(99, 2);
console.log(scores); // [10, 20, 99, 99]

Common Use Cases

Creating an array pre-filled with default values:

const grid = new Array(5);
grid.fill(0);
console.log(grid); // [0, 0, 0, 0, 0]

Resetting a section of an array:

const data = [5, 10, 15, 20, 25];
data.fill(0, 1, 4);
console.log(data); // [5, 0, 0, 0, 25]

Key Takeaway: fill() mutates an array by replacing elements with a single static value across the entire array or a specified range, perfect for initialization or bulk updates.