How to create a zero filled JavaScript array of arbitrary length?

New ES6 array extensions allow you to do this natively with fill method. Now IE edge, Chrome and FF supports it, but check the compatibility table

new Array(3).fill(0) will give you [0, 0, 0]. You can fill the array with any value like new Array(5).fill('abc') (even objects and other arrays).

On top of that you can modify previous arrays with fill:

arr = [1, 2, 3, 4, 5, 6]
arr.fill(9, 3, 5)  # what to fill, start, end

which gives you: [1, 2, 3, 9, 9, 6]


In Javascript ES6 there is a very easy solution. I came here because I'm trying to codegolf it shorter:

n = 999  // arbitrary length
a = Array(n).fill(0)

console.log(a)

By default Uint8Array, Uint16Array and Uint32Array classes keep zeros as it's values, so you don't need any complex filling techniques, just:

var ary = new Uint8Array(10); 

all elements of array ary will be zeros by default.


How about trying like this:

Array.apply(null, new Array(10)).map(Number.prototype.valueOf,0);
//Output as [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

or

new Array(10+1).join('0').split('').map(parseFloat)
//Output as [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

EDIT:-

If your array is dynamic then simply put that in a function which takes a number and replace 10 by that variable.

Tags:

Javascript