Course contentsShow
← JavaScript
Lesson 838 of 2,72319. ArraysFree lesson

Array.of for Creating Arrays from Arguments

Learn how Array.of creates a new array from its arguments, avoiding the pitfalls of the Array constructor.

Array.of for Creating Arrays from Arguments

You'll learn how Array.of() creates arrays from its arguments in a predictable, intuitive way—fixing quirks of the old Array constructor.

The Problem It Solves

When you use the Array constructor with a single number, JavaScript doesn't create an array with that number—it creates an empty array of that length:

const weird = new Array(3); // [empty × 3] - sparse array, length 3
const alsoWeird = new Array(5); // [empty × 5]

This behavior is confusing and different from what happens with multiple arguments:

const normal = new Array(1, 2, 3); // [1, 2, 3] - works as expected

Enter Array.of()

Array.of() treats all arguments uniformly—it creates an array containing exactly those values, no special cases:

const arr1 = Array.of(3); // [3] - array with one element: the number 3
const arr2 = Array.of(5); // [5] - array with one element: the number 5
const arr3 = Array.of(1, 2, 3); // [1, 2, 3] - works the same way
const arr4 = Array.of(); // [] - empty array

Why This Matters

Array.of() is predictable: whatever you pass becomes the array contents. This makes it safer when you don't know how many arguments you'll have, especially when working with dynamic data.

Think of it like ordering pizza: the Array constructor sometimes gives you an empty box when you ask for "3", while Array.of() consistently gives you exactly what you ordered.

When to Use It

Use Array.of() when creating arrays from a variable number of arguments where those arguments should become the array elements, not control its structure.

Key Takeaway: Array.of() creates a new array from its arguments without the confusing single-number quirk of the Array constructor—what you pass is what you get.