Understanding the Purpose of Array.of in JavaScript

In JavaScript, the Array.of method was introduced as part of the ES6 (ECMAScript 2015) specification. At first glance, it might seem redundant. After all, why use Array.of(1, 2, 3) when you can simply declare and initialize an array like this: [1, 2, 3]?

The answer lies in a specific quirk of the Array constructor.

The Quirk of the Array Constructor

In JavaScript, the Array constructor behaves differently based on the number of arguments passed to it. If you pass multiple arguments or a single argument that is not a number, it creates an array with those arguments as elements:

let array = new Array("a", "b", "c");
console.log(array); // Outputs: ['a', 'b', 'c']

However, if you pass a single number to the Array constructor, it creates an array with a length equal to that number, and the array is filled with undefined:

let array = new Array(3);
console.log(array); // Outputs: [undefined, undefined, undefined]

This behavior can lead to confusion and bugs in your code.

The Consistency of Array.of

The Array.of method was introduced to address this quirk. Regardless of the number or type of arguments, Array.of creates a new array instance with the given arguments as elements:

let array = Array.of(3);
console.log(array); // Outputs: [3]

In this case, Array.of(3) creates an array with a single element, 3, which is more intuitive and less error-prone than the Array constructor's behavior.

In conclusion, while it's true that for most use cases, simply declaring and initializing an array with bracket notation ([1, 2, 3]) is simpler and more common, Array.of provides a consistent and less error-prone alternative to the Array constructor when you need to create an array from a dynamic list of arguments.

Get my free, weekly JavaScript tutorials

Want to improve your JavaScript fluency?

Every week, I send a new full-length JavaScript article to thousands of developers. Learn about asynchronous programming, closures, and best practices — as well as general tips for software engineers.

Join today, and level up your JavaScript every Sunday!

Thank you, Taha, for your amazing newsletter. I’m really benefiting from the valuable insights and tips you share.

- Remi Egwuda