This page looks best with JavaScript enabled

Avoid Array Constructors in Javascript

 ·   ·  ☕ 1 min read

Array constructor syntax is confusing to both the system and humans. Avoid it when possible.

Consider this..

1
2
3
const planets = ["mercury", "venus", "earth"];
console.log(planets[0]);
// mercury

Now, let’s say we do the same using a constructor.

1
2
3
4
const num = new Array(3, 1, 4, 5);
console.log("num: ", num); // [ 3, 1, 4, 5 ]

console.log(num[0]); // 3

This is ok, but there is a way to use new Array to specify the number of elements in the array.

1
2
3
const num = new Array(3).fill(0);
console.log("num: ", num);
// [ 0, 0, 0 ]

So, if we provide only one input - does it mean the number of elements, or the first element?

1
2
3
4
5
6
const num = new Array(3);
console.log("num: ", num);
// [ <3 empty items> ]

console.log(num[0]);
// undefined

Avoid confusion by avoiding the Array.new() notation. Use our beloved square brackets to create arrays.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things