Skip to content
Tutorials Center
My learning

Topics

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.

JavaScript
Array.of(7); // [7]
Array(7);    // an empty array with length 7

Try it

JS Array.of() versus the constructor

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS As a factory function

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
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 creates n empty slots, and a non-integer such as new Array(1.5) throws a RangeError.
  • Literal vs Array.of(): [a, b, c] is simpler, faster to read and just as fast to run. Use Array.of() only where a function is required.
  • Subclasses: Queue.of(...) returns an instance of Queue, because of uses this as 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) or new Array(n).fill(value), not Array.of().
  • Callbacks: array.map(Array.of) does not work as you might hope, because map passes (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.