fill() & copyWithin() in JavaScript

From the JavaScript Array Methods cheat sheet · Array Creation & Conversion · verified Jul 2026

fill() & copyWithin()

Fill array with values or copy elements within

javascript
// Fill array with value
[1, 2, 3].fill(0);        // [0, 0, 0]
[1, 2, 3].fill(0, 1);     // [1, 0, 0]
[1, 2, 3].fill(0, 1, 2);  // [1, 0, 3]

// Copy within array
[1, 2, 3, 4, 5].copyWithin(0, 3); // [4, 5, 3, 4, 5]
⚠️ Both methods MUTATE the array
💡 fill() sets multiple elements to same value
📌 copyWithin() copies part to another position
⚡ Useful for array initialization
🔴 Be careful with object references in fill()

More JavaScript tasks

Back to the full JavaScript Array Methods cheat sheet