Array.of vs Array Constructor in JavaScript

Both Array.of() and the Array constructor create new array instances in JavaScript, but they behave very differently when handling a single numeric argument. While the Array constructor treats a single number as the intended length of a sparse array, Array.of() treats any argument as an element of the array. Understanding this fundamental distinction prevents unexpected bugs and ensures consistent array creation in your applications.

The Core Difference

The primary difference lies in how each method interprets a single numerical argument.

The Array Constructor Behavior

The Array constructor has overloaded behavior depending on the number and type of arguments passed to it:

  1. Single Numeric Argument: It creates an empty array with its length property set to that number. It does not populate the array with values.
  2. Multiple Arguments or Single Non-Numeric Argument: It creates an array containing the passed arguments as elements.
// Single numeric argument creates empty slots
const emptySlots = new Array(3);
console.log(emptySlots); // [ <3 empty items> ]
console.log(emptySlots.length); // 3

// Multiple arguments create elements
const numbers = new Array(1, 2, 3);
console.log(numbers); // [1, 2, 3]

// Single non-numeric argument creates an element
const singleString = new Array('hello');
console.log(singleString); // ['hello']

Passing a negative number or a non-integer float to new Array() throws a RangeError: Invalid array length.

The Array.of() Behavior

Introduced in ES6 (ECMAScript 2015), Array.of() provides consistent behavior regardless of the number or type of arguments. It always creates an array whose elements are the arguments provided.

// Single numeric argument creates an array with that element
const singleNum = Array.of(3);
console.log(singleNum); // [3]
console.log(singleNum.length); // 1

// Multiple arguments
const multipleNums = Array.of(1, 2, 3);
console.log(multipleNums); // [1, 2, 3]

// Non-integer and negative numbers do not throw errors
const floatNum = Array.of(3.5);
console.log(floatNum); // [3.5]

Comparison Summary

Feature new Array(...) Array.of(...)
Single Number (e.g., 3) [ <3 empty items> ] (length: 3) [3] (length: 1)
Multiple Numbers (1, 2) [1, 2] [1, 2]
Single Non-Number ('a') ['a'] ['a']
Invalid Array Length (-1, 1.5) Throws RangeError [-1], [1.5]

Subclassing Support

Array.of() is a factory method that respects subclassing. When called on a subclass constructor, it returns an instance of that subclass:

class CustomArray extends Array {}

const custom = CustomArray.of(1, 2, 3);
console.log(custom instanceof CustomArray); // true
console.log(custom); // CustomArray(3) [1, 2, 3]

When to Use Which