160

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

Psuedo code:

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

output:

   myarray = ["","",""]
3

9 Answers 9

375

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]

7
  • 1
    Array.prototype.fill (>=ES6) kangax.github.io/compat-table/es6/…;
    – ptim
    Jul 20, 2017 at 3:18
  • 7
    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 9, 2017 at 1:03
  • What is the size of Array(10000) with empty x 10000?
    – Qwerty
    Apr 13, 2018 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, 2018 at 8:26
  • Array.apply('x', Array(10)) is actually [undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined]
    – Polv
    Aug 4, 2018 at 9:13
101
var arr = new Array(5);
console.log(arr.length) // 5
3
  • 16
    The OP asked in javascript how would I create an empty array of a given size. This solves that problem.
    – mariocatch
    Jan 22, 2016 at 1:21
  • 16
    The OP has provided an example of "empty".
    – RobG
    Jan 22, 2016 at 1:22
  • 9
    Well this is another option to the question. They can choose any of the answers provided, that's the glory of stackoverflow :)
    – mariocatch
    Jan 22, 2016 at 1:24
62

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

3
  • @gion_13: I see it being voted up and mine being voted down. Reason?
    – 7vujy0f0hy
    Apr 15, 2018 at 2:02
  • 1
    @7vujy0f0hy I don’t know why you got down votes. I gave you an up vote, although your solution is a bit less intuitive than this one.
    – gion_13
    Apr 15, 2018 at 5:17
  • @gion_13: Thanks for confirming there’s nothing wrong with my solution ☺.
    – 7vujy0f0hy
    Apr 15, 2018 at 9:56
35

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('');
5
  • 9
    new Array(2) doesn't give you [undefined, undefined]. It gives you an array that isn't iterable.
    – JCF
    Sep 4, 2019 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 4, 2019 at 17:58
  • 2
    @JCF for...of uses iterator protocol, so it behaves differently than forEach/map. Iterators loose emptiness information Mar 12, 2020 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, 2020 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, 2020 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("");
1
  • 1
    .fill() is an elegant one liner solution. Thanks!
    – colefner
    Jan 17, 2019 at 22:58
21

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

3
  • 3
    into the future!
    – Levi
    Jan 22, 2020 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, 2020 at 3: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. Jul 15, 2020 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)

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>

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.