JS Built-ins
ArrayArrayintermediate

Array() β€” create a range [1…n]

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

Spread new Array(n).keys() to generate a compact 0-based index range array.

Array constructor β€” creating a range

To produce [1, 2, 3, …, n] you can combine new Array(n) (which creates n empty slots) with Array.from and a mapping function, or spread the result of Array(n).keys().

Challenge: Implement createRange that returns [1, 2, …, n].

createRange(5) // β†’ [1, 2, 3, 4, 5]
createRange(1) // β†’ [1]
πŸ’‘ Hints (2)
  • β€’ `Array.from(new Array(n), (_, i) => i + 1)` maps each slot index to `index + 1`.
  • β€’ You could also do `[...Array(n).keys()].map(i => i + 1)`.