JS Built-ins
← Array60 / 226
ArrayArray.prototype.fillintermediate

Array.prototype.fill() β€” create zero-filled array

πŸ“– Usage Example
const zeros = new Array(5).fill(0)
zeros  // β†’ [0, 0, 0, 0, 0]

Combine new Array(n) with fill(0) to create a zero-initialized array of length n.

Array.prototype.fill() β€” initializing arrays

A common pattern is to create a fixed-length array initialized to a default value. new Array(n).fill(0) creates an n-element array of zeros without using a loop.

Challenge: Implement createMatrix(n) that returns an array of n zeros.

createMatrix(5) // β†’ [0, 0, 0, 0, 0]
createMatrix(0) // β†’ []
πŸ’‘ Hints (2)
  • β€’ `new Array(n)` creates a sparse array with `n` slots β€” without `.fill()` each slot is `empty`.
  • β€’ `.fill(0)` replaces every sparse slot with an actual `0` value.