131

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

Psuedo code:

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

output:

   myarray = ["","",""]
SCdF
  • 54,293
  • 24
  • 75
  • 111
gus
  • 1,468
  • 2
  • 11
  • 10
  • 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

8 Answers8

320

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
  • 4,673
  • 2
  • 10
  • 22
  • 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
92
var arr = new Array(5);
console.log(arr.length) // 5
mariocatch
  • 7,753
  • 7
  • 45
  • 69
55

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

andrewkslv
  • 1,191
  • 11
  • 14
24

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
  • 10,672
  • 4
  • 37
  • 67
jeffdill2
  • 3,628
  • 2
  • 26
  • 43
  • 5
    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
21

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
  • 12
  • 91
  • 170
18

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

7vujy0f0hy
  • 7,492
  • 1
  • 25
  • 31
  • 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
5

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
  • 858
  • 8
  • 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.
  • 932
  • 1
  • 10
  • 10