Lodash/underscore function to Initialize an array with default null values of a given length

That should do the tricks:

_.times(arrayLength, _.constant(null));

eg:

_.times(5, _.constant(null));
[null, null, null, null, null]

_.fill(Array(arrayLength), null)

// exemple:
_.fill(Array(5), null); // [ null, null, null, null, null ]

EDIT:

I made some performance tests: https://jsperf.com/lodash-initialize-array-fill-vs-times

  • _.fill is faster than _.times
  • null is faster than _constant(null)

I'd suggest using _.fill

_.fill(Array(myArrayLength), null);`

It seems to be faster than _.times, at least it is on Chrome.

See perf comparison here: https://jsperf.com/fill-vs-times/1