Array Constructor vs Array.of
You'll learn why Array(3) and Array.of(3) produce surprisingly different results and when to use each.
The Confusing Behavior of the Array Constructor
The Array() constructor has a quirky special case: when you pass it a single number, it doesn't create an array containing that number. Instead, it creates an empty array of that length:
const arr1 = Array(3);
console.log(arr1); // [empty × 3] (sparse array with 3 empty slots)
console.log(arr1.length); // 3
console.log(arr1[0]); // undefined
const arr2 = Array(5, 10, 15);
console.log(arr2); // [5, 10, 15] (works as expected with multiple arguments)
This inconsistency can cause bugs, especially when creating arrays programmatically.
Array.of() to the Rescue
Array.of() was introduced to solve this confusion. It always creates an array containing the arguments you pass, treating all inputs uniformly:
const arr1 = Array.of(3);
console.log(arr1); // [3] (an array containing the number 3)
const arr2 = Array.of(5, 10, 15);
console.log(arr2); // [5, 10, 15]
const arr3 = Array.of('hello');
console.log(arr3); // ['hello']
When to Use Each
Use Array.of() when you want to create an array from values, especially when the number of values is dynamic or might be just one.
Use Array(length) only when you specifically need to pre-allocate a sparse array of a certain size (though this is rare in practice).
Key Takeaway: Array(3) creates an empty array with length 3, while Array.of(3) creates an array containing the value 3. Prefer Array.of() for predictable, value-based array creation.