Course contentsShow
← JavaScript
Lesson 890 of 2,72320. Array Iteration and TransformationFree lesson

The Array.prototype.fill() Method

Learn how fill() replaces array elements with a static value, accepting start and end indices.

The Array.prototype.fill() Method

What you'll learn: How to use fill() to replace multiple array elements with a single static value in one operation.

What Is fill()?

The fill() method is a mutating array method that replaces array elements with a static value. Unlike methods that transform each element individually, fill() stamps the same value into every targeted position. Think of it like using a paint roller to cover a wall section with one color—quick, uniform, and efficient.

Basic Syntax

array.fill(value, start, end)
  • value: The static value to insert
  • start (optional): Index to begin filling (default: 0)
  • end (optional): Index to stop before (default: array.length)

How It Works

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

With start and end indices:

const letters = ['a', 'b', 'c', 'd', 'e'];
letters.fill('x', 1, 4);
console.log(letters); // ['a', 'x', 'x', 'x', 'e']

Notice that index 4 is not included—fill() works up to but not including the end index.

Common Use Cases

Initializing arrays:

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

Resetting a portion:

const scores = [10, 20, 30, 40, 50];
scores.fill(0, 2); // Reset from index 2 onward
console.log(scores); // [10, 20, 0, 0, 0]

Important Notes

  • fill() mutates the original array
  • Returns the modified array (useful for chaining)
  • Works with negative indices (counting from the end)
  • Fills with the same reference for objects/arrays

Key Takeaway: Use fill() to efficiently replace multiple array elements with the same static value, optionally targeting specific index ranges with start and end parameters.