JS Built-ins
← Array28 / 226
ArrayArray.ofbeginner

Array.of() β€” avoid the single-number trap

πŸ“– Usage Example
// Ambiguous new Array:
new Array(3)         // β†’ [empty x 3]  (sparse)
new Array(1, 2, 3)   // β†’ [1, 2, 3]
// Always predictable Array.of:
Array.of(3)          // β†’ [3]

Prefer Array.of() over new Array() for clarity β€” its behavior is consistent regardless of argument count.

Array.of() vs new Array()

new Array(7) creates a sparse array with 7 empty slots, not an array containing 7. Array.of(7) always creates an array whose single element is 7. This distinction makes Array.of safer when you only have one value.

Challenge: Implement safeArrayOf that always wraps n in an array (i.e. returns [n]), never a sparse array of length n.

safeArrayOf(7)   // β†’ [7]   not [ <7 empty slots> ]
safeArrayOf(0)   // β†’ [0]
πŸ’‘ Hints (2)
  • β€’ `Array.of(n)` always creates `[n]` regardless of what `n` is.
  • β€’ `new Array(n)` treats a single numeric argument as the desired length, not a value.