JS Built-ins
← Array29 / 226
ArrayArray.ofbeginner

Array.of() β€” wrap a single value

πŸ“– Usage Example
Array.of(42)    // β†’ [42]   (element)
new Array(42)   // β†’ (42 empty slots)  (length!)

Array.of(n) with a single number creates a one-element array; new Array(n) creates n empty slots.

Array.of() β€” generic wrapping

Because Array.of() is generic, it works with any value type. It is a clean, intention-revealing alternative to the literal [val] when you want to be explicit that you are wrapping a single value.

Challenge: Implement wrapInArray that takes any value and returns it inside a single-element array using Array.of.

wrapInArray(42)      // β†’ [42]
wrapInArray('hello') // β†’ ['hello']
wrapInArray(null)    // β†’ [null]
πŸ’‘ Hints (2)
  • β€’ `Array.of(val)` is equivalent to `[val]` but communicates intent clearly.
  • β€’ The generic `<T>` ensures the return type is inferred correctly by TypeScript.