152

in javascript how would I create an empty array of a given size

Psuedo code:

X = 3;
createarray(myarray, X, "");

output:

   myarray = ["","",""]
SCdF
  • 57,260
  • 24
  • 77
  • 113
gus
  • 1,678
  • 2
  • 12
  • 11
  • 5
    You'd probably use [*Array.prototype.fill*](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/fill). – RobG Jan 22 '16 at 01:17
  • Possible duplicate of [default array values](https://stackoverflow.com/questions/2044760/default-array-values) – Nick Grealy Jun 27 '17 at 00:20
  • Related post [here](https://stackoverflow.com/q/4852017/465053). – RBT Oct 09 '17 at 00:54

9 Answers9

361

1) To create new array which, you cannot iterate over, you can use array constructor:

Array(100) or new Array(100)


2) You can create new array, which can be iterated over like below:

a) All JavaScript versions

  • Array.apply: Array.apply(null, Array(100))

b) From ES6 JavaScript version

  • Destructuring operator: [...Array(100)]
  • Array.prototype.fill Array(100).fill(undefined)
  • Array.from Array.from({ length: 100 })

You can map over these arrays like below.

  • Array(4).fill(null).map((u, i) => i) [0, 1, 2, 3]

  • [...Array(4)].map((u, i) => i) [0, 1, 2, 3]

  • Array.apply(null, Array(4)).map((u, i) => i) [0, 1, 2, 3]

  • Array.from({ length: 4 }).map((u, i) => i) [0, 1, 2, 3]

stpoa
  • 5,223
  • 2
  • 14
  • 26
  • 1
    Array.prototype.fill (>=ES6) https://kangax.github.io/compat-table/es6/#test-Array.prototype_methods_Array.prototype.fill_a_href=_https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill_title=_MDN_documentation_img_src=_../mdn.png_alt=_MDN_(Mozilla_Development_Network)_logo_width=_15_height=_13_/_/a_nbsp; – ptim Jul 20 '17 at 03:18
  • 5
    Enlightenment of the day - when you mention in part (A) that a newly created array using constructor syntax is not even iteratable. Javascript really surprises at times. – RBT Oct 09 '17 at 01:03
  • What is the size of `Array(10000)` with `empty x 10000`? – Qwerty Apr 13 '18 at 14:26
  • 1
    Its length is 10000, you can check it by `console.log(Array(10000).length)` But if you run `Array(10000).forEach((u, i) => console.log(i))`, you will get no output – stpoa Apr 16 '18 at 08:26
  • `Array.apply('x', Array(10))` is actually `[undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined]` – Polv Aug 04 '18 at 09:13
  • Someone please explain 1). Why can't you iterate? – Santiago Dandois Aug 22 '22 at 19:20
  • Also `Array.from({ length:4 }, (u, i) => i)` – Qwerty Feb 21 '23 at 01:42
98
var arr = new Array(5);
console.log(arr.length) // 5
mariocatch
  • 8,305
  • 8
  • 50
  • 71
61

We use Array.from({length: 500}) since 2017.

andrewkslv
  • 1,279
  • 12
  • 14
29

As of ES5 (when this answer was given):

If you want an empty array of undefined elements, you could simply do

var whatever = new Array(5);

this would give you

[undefined, undefined, undefined, undefined, undefined]

In newer versions, this now gives

[empty × 5]

See this other question on the difference between empty and undefined.

If you wanted it to be filled with empty strings, you could do

whatever.fill('');

which would give you

["", "", "", "", ""]

And if you want to do it in one line:

var whatever = Array(5).fill('');
codeling
  • 11,056
  • 4
  • 42
  • 71
jeffdill2
  • 3,968
  • 2
  • 30
  • 47
  • 9
    new Array(2) doesn't give you [undefined, undefined]. It gives you an array that isn't iterable. – JCF Sep 04 '19 at 11:21
  • 1
    OK. There's something else going on I don't understand. I'm creating a new array with `new Array(2)` and what I get back is `[ <2 empty items> ]` not `[undefined, undefined]`. Using `.map` on the former has no effect. However, I can iterate over it using a `for...of` loop. If I create a new array using literal notation `a = [undefined, undefined]` then I can use `.map` on it. – JCF Sep 04 '19 at 17:58
  • 2
    @JCF for...of uses iterator protocol, so it behaves differently than forEach/map. Iterators loose emptiness information – Tomasz Błachut Mar 12 '20 at 10:30
  • 2
    @TomaszBłachut @JCF For the down-voters, please keep in mind that this answer was given over 4 years ago – at which time, this answer was 100% valid. ES6 and ES7 did not start rolling out to browsers until mid-2016 and mid-2018, respectively. At the time of this answer, the JS version would have been ES5. If you need further proof that this _is_ the way ES5 worked, simply spin up an older instance of Chrome – at the time of this answer, it would have been v48 – and run `Array(5)`. You will see the following output: `[undefined x 5]`. – jeffdill2 Mar 12 '20 at 13:46
  • 2
    @jeffdill2 It's best to add new information to the answer itself. The comments are not always fully read. – Boaz May 12 '20 at 13:19
22

Try using while loop, Array.prototype.push()

var myArray = [], X = 3;
while (myArray.length < X) {
  myArray.push("")
}

Alternatively, using Array.prototype.fill()

var myArray = Array(3).fill("");
guest271314
  • 1
  • 15
  • 104
  • 177
20

In 2018 and thenceforth we shall use [...Array(500)] to that end.

7vujy0f0hy
  • 8,741
  • 1
  • 28
  • 33
  • 2
    into the future! – Levi Jan 22 '20 at 23:46
  • Hilariously this (and similar) is 50% slower than just ``(() => { let n = []; for(var i=0;i<500;i++){y.push("");} return n; })()``. – Alex Apr 24 '20 at 03:51
  • That reeks of premature optimization, maybe if you're intending to create a bunch of arrays with tens of millions of elements you might want to consider it but a few nanoseconds, for most cases, isn't going to make it worth the readability hit. – JaredMcAteer Jul 15 '20 at 19:15
6

If you want to create anonymous array with some values so you can use this syntax.

var arr = new Array(50).fill().map((d,i)=>++i)
console.log(arr)
manan5439
  • 898
  • 9
  • 24
1

You can use both javascript methods repeat() and split() together.

" ".repeat(10).split(" ")

This code will create an array that has 10 item and each item is empty string.

const items = " ".repeat(10).split(" ")

document.getElementById("context").innerHTML = items.map((item, index) => index)

console.log("items: ", items)
<pre id="context">

</pre>
Serhan C.
  • 1,152
  • 1
  • 12
  • 10
0

I've created benchmark tests for generating the empty arrays for iteration. The spread operator is the fastest. Array.from({length:n}) is the slowest.

  • Array.apply(null, Array(n)).map()
  • [...Array(n)].map()
  • Array(n).fill(null).map()
  • Array.from({ length: n }).map()
  • Array.from({ length:n }, (item, i) => i)

https://www.measurethat.net/Benchmarks/Show/25596/1/compare-the-ways-to-generate-an-empty-array-for-iterati enter image description here

Neo
  • 31
  • 4