JavaScript Reference ยท Array
Array.of()
Reference for JavaScript Array.of(): create an array from its arguments, how it differs from the Array() constructor with a single number, and subclass use.
Array.of() creates a new array whose elements are exactly the arguments you pass, whatever their number or type. It exists to remove one quirk of the Array() constructor: new Array(3) makes an empty array of length 3, while Array.of(3) makes an array with the single element 3.
For everyday code, an array literal such as [3] does the same thing and is shorter. Array.of() matters when you need a function that builds arrays, for example as a factory you pass around or call on a subclass.
Array.of(7); // [7] Array(7); // an empty array with length 7
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
Array.of(element0) Array.of(element0, element1, /* โฆ */ elementN)
| Name | Description |
|---|---|
element0, โฆ, elementN |
The values that become the array elements, in order. |
Return value: a new Array instance containing the arguments.
Exceptions: none for normal calls.
Usage notes
- No special case for one number. This is the whole reason it exists.
new Array(n)with a single number createsnempty slots, and a non-integer such asnew Array(1.5)throws aRangeError. - Literal vs
Array.of():[a, b, c]is simpler, faster to read and just as fast to run. UseArray.of()only where a function is required. - Subclasses:
Queue.of(...)returns an instance ofQueue, becauseofusesthisas the constructor.[...]literals always create plain arrays. - Elements are stored as given. Nothing is copied, so passing objects stores references.
- Filling an array of a given length is a job for
Array.from({ length: n }, fn)ornew Array(n).fill(value), notArray.of(). - Callbacks:
array.map(Array.of)does not work as you might hope, becausemappasses(value, index, array), which creates[value, index, array]arrays. Use a wrapper such as(x) => [x].
Browser support
Array.of() is supported in every current browser and JavaScript runtime.