Initialize number array in Javascript

Sophia’s first version of iPad

Create an array in Javascript isn’t 100% straightforward as in other languages. Although on the surface it does seem simple, and most of the online tutorial can put you in the right (working) direction. Does it occur to you it’s not well designed?

Consider the following array statement, what’s odd is that

  • the elements aren’t initialized, so you can’t apply map right away
  • the element type has to be resolved after the fill

There’re many libraries (even ES6) extending the array functionalities, but they rarely talk about the definition or the initialization of the array. Things seem to be just born as that.

Over the years of solving practical problem, I tend to ask myself to write a more practical array statement like below,

Just to be more precise,

Let’s see if we can address some problems with it.

  • use element index as its default value
  • can assign custom initial value (or function)
  • can set element type with fixed size (see appendix)

If you use this definition, you’ll end up with less trouble initializing it with the right size.

Be care trying large N, one million (with six zeros) should be ok, but eight zeros above will most likely give you hard time. A common sense here is that if you can’t handle one million, you seriously have a problem (bug) in your program.


You can check the documentation of typed array to find out how much memory you need to hold a fixed type.

You can also use the following line to better understand the real memory allocated to your node instance.

Front-end Engineer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store