Consistent array construction
Build an array from a dynamic argument list without special handling for a single numeric value.
JavaScript · Function
Array.of() creates a new array from its arguments, regardless of how many arguments there are or what types they have. A single number is stored as an element, unlike with Array().
Array.of() creates and returns a new Array containing its arguments in order. Unlike the Array constructor, one numeric argument becomes an element rather than an array length; the method can also be inherited by array subclasses or called with another suitable constructor.
Array.of()
Array.of(element1)
Array.of(element1, element2)
Array.of(element1, element2, /* …, */ elementN)| Name | Type | Description |
|---|---|---|
element1, …, elementN | any | The values to place into the newly created array, in argument order. |
A new Array instance.
const single = Array.of(7);
const many = Array.of(1, 2, 3);
const empty = Array.of();
console.log(single); // [7]
console.log(many); // [1, 2, 3]
console.log(empty); // []The method creates arrays whose elements are exactly the supplied arguments, including when there is one argument or none.
Build an array from a dynamic argument list without special handling for a single numeric value.
Create a one-element array containing a number, including zero or another length-like value.
Use an inherited static factory when an Array subclass should receive the result.
Array.of() is a static factory that returns a new Array containing all supplied arguments in order. It also supports zero arguments and preserves each argument as an element.
Follow-up: What does Array.of(7) return compared with Array(7)? Array.of(7) returns [7], whereas Array(7) creates an array with length 7 and empty slots.
Array.of(7) treats 7 as the first element, so the result is [7]. Array(7) interprets the single numeric argument as the desired length and creates empty slots instead.
Follow-up: What happens with Array.of(undefined)? It returns an array containing one element whose value is undefined.
The method is generic and uses its this value as the constructor for the result. An inherited call can therefore create an instance of an Array subclass, provided the constructor accepts the length argument used by the method.
Follow-up: Can any constructor be used? Yes, the documentation says the this value can be any constructor function that accepts one argument representing the new array's length.
Array()Array.from()Array.isArray()Array.prototype