JS Built-ins
← Array119 / 226
ArrayArray.prototype.keysintermediate

Array.prototype.keys() β€” keys over sparse arrays

πŸ“– Usage Example
const sparse = [1, , , 4]
[...sparse.keys()]  // β†’ [0, 1, 2, 3]  (includes holes)

keys() yields indices for every slot including holes in sparse arrays.

Array.prototype.keys() β€” sparse arrays

Unlike forEach or map, keys() iterates over every index, including holes in sparse arrays. new Array(n) creates a sparse array with n holes β€” keys() still yields 0 through n-1.

Challenge: Implement sparseKeys(n) that returns all indices of a sparse array of length n.

sparseKeys(3) // β†’ [0, 1, 2]
sparseKeys(0) // β†’ []
πŸ’‘ Hints (3)
  • β€’ `new Array(n)` creates a sparse array with `n` holes β€” no actual values, but `length === n`.
  • β€’ `keys()` visits every slot, including holes, so you get indices 0 through n-1.
  • β€’ This pattern is a common way to generate a range of numbers.