Array.of(): build arrays without length traps (ES2015)
What you’ll learn
Section titled “What you’ll learn”- Why
new Array(n)behaves differently with one numeric argument, and howArray.of()avoids it. - How
Array.of()works with subclasses and typed arrays. - The
map(Array.of)pitfall and other edge cases. - When you should simply write an array literal, or use
Array.from()instead.
Summary
Section titled “Summary”TL;DR: Array.of(...items) returns a new array whose elements are exactly its arguments. Unlike the Array constructor, a single number is an element, not a length: Array.of(3) is [3], while Array(3) is an empty array of length 3.
It was added in ECMAScript 2015 and works in every current browser and runtime.
The problem it solves
Section titled “The problem it solves”The Array constructor has two meanings. With one numeric argument it creates a sparse array of that length; with anything else it creates an array of the arguments. A non-integer number throws.
Running the samples: save a sample as a .mjs file and run it with Node.js 22 (node sample.mjs), or paste it into a browser console. The outputs shown were produced with Node.js 22.23.
// The Array constructor treats a single number as a length.console.log(Array(3)); // [ <3 empty items> ]console.log(Array(3, 4)); // [ 3, 4 ]console.log(Array('3')); // [ '3' ]try { Array(2.5); } catch (e) { console.log(e.constructor.name, '-', e.message); }// RangeError - Invalid array length
// Array.of always treats its arguments as elements.console.log(Array.of(3)); // [ 3 ]console.log(Array.of(3, 4)); // [ 3, 4 ]console.log(Array.of(2.5)); // [ 2.5 ]console.log(Array.of()); // []console.log(Array.of(undefined)); // [ undefined ]In hand-written code you would write [3], so the trap rarely bites directly. It bites when the arguments are dynamic: spread into new Array(...values), or a subclass constructor that forwards its arguments to super().
How it works
Section titled “How it works”// Fragment: signatureArray.of(element0, element1, /* ... */ elementN) // new arrayThe specification steps are:
- Count the arguments.
- If
thisis a constructor, callnew this(count); otherwise create a plain array. - Define each argument as an element, then set
length.
Step 2 makes Array.of() an intentionally generic factory. Called as Array.of, it builds an Array. Inherited by a subclass, as MyList.of(...), it builds a MyList. Called with no usable this, for example after destructuring const { of } = Array, it still returns a plain array. Typed arrays have their own of() (such as Uint8Array.of()), which converts each argument to the element type and requires a typed-array constructor as this.
// Passing Array.of as a callback: map supplies (value, index, array), and Array.of keeps all three.console.log([1042, 1043].map(Array.of));// [ [ 1042, 0, [ 1042, 1043 ] ], [ 1043, 1, [ 1042, 1043 ] ] ]console.log([1042, 1043].map((n) => Array.of(n))); // [ [ 1042 ], [ 1043 ] ]
// Array.of is generic: it uses `this` as the constructor when it can.console.log(Array.of.call(Object, 'a', 'b')); // [Number: 2] { '0': 'a', '1': 'b', length: 2 }const { of } = Array;console.log(of(1, 2)); // [ 1, 2 ] (this is undefined, not a constructor, so a plain array)The Object case shows the mechanics: new Object(2) is a Number wrapper object, and the elements and length are added to it. You will not need that in practice, but it explains why the subclass case works.
Realistic example
Section titled “Realistic example”OrdersPortal groups order numbers into warehouse batches. A helper that spreads its arguments into the Array constructor works in tests with several orders and fails in production the first time a batch holds one order. The same trap applies to Array subclasses, and typed arrays use of() for fixed byte sequences.
// order-batch.mjs - OrdersPortal groups order numbers into a batch for the warehouse.
// Buggy: spreading arguments into the Array constructor.function makeBatchBuggy(...orderNumbers) { return new Array(...orderNumbers);}console.log(makeBatchBuggy(1041, 1042)); // [ 1041, 1042 ]console.log(makeBatchBuggy(1042).length); // 1042 <- one order became 1042 empty slots
// Fixed: Array.of never interprets a number as a length.function makeBatch(...orderNumbers) { return Array.of(...orderNumbers);}console.log(makeBatch(1042)); // [ 1042 ]
// Subclasses inherit Array.of, and it builds an instance of the subclass.class OrderBatch extends Array { get count() { return this.length; } describe() { return `Batch of ${this.count}: ${this.join(', ')}`; }}const batch = OrderBatch.of(1042);console.log(batch instanceof OrderBatch, batch.describe()); // true Batch of 1: 1042console.log(new OrderBatch(1042).count); // 1042 <- same constructor trap
// Typed arrays have their own of(): handy for fixed byte sequences.const header = Uint8Array.of(0x4f, 0x50, 0x01); // "OP" magic bytes + format version 1console.log(header); // Uint8Array(3) [ 79, 80, 1 ]makeBatch could also return the rest parameter orderNumbers directly, since it is already a fresh array. Array.of() earns its place when you need the subclass instance, or when the factory is passed around as a value.
Common mistakes
Section titled “Common mistakes”- Spreading dynamic values into
new Array(...). One numeric value turns into a length, and a non-integer throwsRangeError. UseArray.of(...values)or[...values]. - Passing
Array.ofstraight tomap().mapcalls it with(value, index, array), so each result has three elements. Wrap it:map((v) => Array.of(v)), ormap((v) => [v]). - Confusing it with
Array.from().Array.of('abc')is['abc'];Array.from('abc')iterates the string into['a', 'b', 'c']. - Expecting a pre-sized array. To create
nslots,Array.of(n)is wrong; useArray.from({ length: n }, fn)ornew Array(n).fill(value). - Destructuring
TypedArray.of.const { of } = Uint8Array; of(1)throwsTypeError: undefined is not a constructorbecause typed-arrayof()needs itsthis.
When to use it and when not to
Section titled “When to use it and when not to”| You want | Use |
|---|---|
| A fixed list written in code | an array literal: [1042] |
| An array from a dynamic argument list | Array.of(...values) or [...values] |
An instance of an Array subclass from elements |
MyArray.of(...values) |
| A typed array from literal values | Uint8Array.of(...), Float64Array.of(...) |
| An array from an iterable or array-like, optionally mapped | Array.from() |
An array of n generated values |
Array.from({ length: n }, (_, i) => ...) |
Prefer literals in everyday code: they are shorter and have no trap. Array.of() is for factories, subclasses and typed arrays.
Compatibility
Section titled “Compatibility”According to MDN’s browser compatibility data, Array.of() is supported in Chrome 45, Edge 12, Firefox 25, Safari 9, Node.js 4, Deno 1.0 and Bun 1.0; TypedArray.of() needs Chrome 45, Firefox 38, Safari 10 and Node.js 4. Internet Explorer never supported it. TypeScript declares it in lib.es2015.core.d.ts as of<T>(...items: T[]): T[].
Interview questions
Section titled “Interview questions”1. What is the difference between Array(7) and Array.of(7)?
Array(7) creates an empty (sparse) array with length 7 and no elements. Array.of(7) creates [7]. With two or more arguments, or one non-number, both produce an array of the arguments.
2. Why does [1, 2].map(Array.of) return nested arrays of three elements?
map calls its callback with the value, the index and the whole array, and Array.of turns every argument into an element. Wrap it in an arrow function that passes only the value.
3. Senior scenario: your team has class Matrix extends Array and several factory helpers that call new Matrix(...rows). Rare inputs produce wrong lengths. How do you fix and prevent it?
new Matrix(...rows) hits the Array constructor’s length rule when there is exactly one numeric argument. Replace the factories with Matrix.of(...rows) or Matrix.from(rows), which build a Matrix without that ambiguity, and keep the constructor’s single-argument behavior intact, because built-in methods such as map() and filter() call new Matrix(length) through Symbol.species. Add a test with a single numeric row, and enable ESLint’s no-array-constructor rule, which flags multi-argument and spread new Array(...) calls (checked with ESLint 9.39), to catch the same pattern for plain arrays.
Key takeaways
Section titled “Key takeaways”Array.of(...items)(ES2015) always makes its arguments the elements; one number is never a length.- It is generic: subclasses inherit it and get instances of themselves; typed arrays have their own
of(). - Do not pass it directly to
map(), and do not confuse it withArray.from(). - In everyday code, prefer array literals; use
Array.of()for dynamic arguments, subclasses and typed arrays.
Related pages
Section titled “Related pages”- Array.from(): create arrays from iterables and array-likes, with an optional map function.
- Spread and rest:
[...values]and rest parameters. - Classes: extending built-ins such as
Array. - Shared memory:
SharedArrayBuffer,Atomicsand typed arrays. - Array find() and findIndex() and Array includes(): other ES2015-era array methods.
- JavaScript arrays
Official references
Section titled “Official references”- ECMAScript Language Specification:
Array.ofand%TypedArray%.of(current draft; first published in ECMAScript 2015) - ECMAScript 2015 Language Specification:
Array.of - MDN: Array.of()
- MDN: TypedArray.of()
- MDN: Array() constructor