Creating and filling Arrays of arbitrary lengths in JavaScript
Update 2019-01-02: Rewrote the section on performance. Switched from Array.from(new Array(LEN)) to Array.from({length: LEN}) (because the former argument can get large). New sections: “Recommended patterns”, “Acknowledgements”.
The best way of creating an Array, is via a literal:
Alas, that isn’t always an option, e.g. when creating large Arrays. This blog post examines what to do in those cases.

Arrays without holes tend to perform better #
In most programming languages, an array is a contiguous sequence of values. In JavaScript, an Array is a dictionary that maps indices to elements. It can have holes – indices between zero and the length, that are not mapped to elements (“missing indices”). For example, the following Array has a hole at index 1:
Arrays without holes are also called dense or packed . Dense Arrays tend to perform better, because they can be stored contiguously (internally). Once there is at least one hole, the internal representation has to change. Two options are:
- A dictionary. Then lookup takes more time and storage overhead is greater.
- A contiguous data structure, with sentinel values for holes. Then checking if a value is a hole or not, takes extra time.
In either case, if an engine encounters a hole, it can’t just return undefined , it must traverse the prototype chain and search for a property whose name is the index of the hole. That costs even more time.
In some engines, such as V8, the switch to a less performant data structure is permanent. They won’t switch back, even if all holes are plugged.
For more on how V8 represents Arrays, consult “ Elements kinds in V8 ” by Mathias Bynens .
Creating Arrays #
Array constructor #.
One common way of creating an Array with a given length, is to use the Array constructor:
This approach is convenient, but it has two downsides:
- The holes make this Array slightly slower, even if you completely fill it with values later on.
- Holes are rarely good initial “values” for elements. E.g., zeros are much more common.
Array constructor plus .fill() method #
The .fill() method changes an existing Array and fills it with a specified value. That helps with initializing an Array after creating it via new Array() :
Caveat: If you .fill() an Array with an object, all elements refer to the same instance (i.e., the object isn’t cloned):
We’ll later encounter a way of filling (via Array.from() ) that doesn’t have this issue.
.push() method #
This time, we have created and filled an Array without putting holes in it. Therefore, using the Array after its creation should be faster than with the Array constructor. Alas, creating the Array is slower, because engines may have to reallocate the contiguous internal representation several times – as it grows.
Filling Arrays with undefined #
Array.from() converts iterables and Array-like values to Arrays. It treats holes as if they were undefined elements. We can use that to convert each hole to an undefined :
The parameter {length: 3} is an Array-like object with length 3 that contains only holes. It is also possible to instead use new Array(3) , but that usually creates larger objects.
Spreading into Arrays only works for iterable values and has a similar effect to Array.from() :
Alas, Array.from() creates its result via new Array() , so you still end up with a sparse Array.
Mapping with Array.from() #
You can use Array.from() to map, if you provide a mapping function as its second parameter.
Filling an Array with values #
- Creating an Array with small integers: > Array.from({length: 3}, () => 0) [ 0, 0, 0 ]
- Creating an Array with unique (unshared) objects: > Array.from({length: 3}, () => ({})) [ {}, {}, {} ]
Creating ranges of integer values #
- Creating an Array with ascending integers: > Array.from({length: 3}, (x, i) => i) [ 0, 1, 2 ]
- Creating an arbitrary range of integers: > const START=2, END=5; > Array.from({length: END-START}, (x, i) => i+START) [ 2, 3, 4 ]
Another way of creating an Array with ascending integers is via .keys() , which also treats holes as if they were undefined elements:
.keys() returns an iterable. We use spreading to convert it to an Array.
Cheat sheet: creating Arrays #
Filled with holes or undefined :
- new Array(3) → [ , , ,]
- Array.from({length: 2}) → [undefined, undefined]
- [...new Array(2)] → [undefined, undefined]
Filled with arbitrary values:
- const a=[]; for (let i=0; i<3; i++) a.push(0); → [0, 0, 0]
- new Array(3).fill(0) → [0, 0, 0]
- Array.from({length: 3}, () => ({})) → [{}, {}, {}] (unique objects)
Ranges of integers:
- Array.from({length: 3}, (x, i) => i) → [0, 1, 2]
- const START=2, END=5; Array.from({length: END-START}, (x, i) => i+START) → [2, 3, 4]
- [...new Array(3).keys()] → [0, 1, 2]
Recommended patterns #
I prefer the following approaches. My focus is on readability, not on performance.
- Do you need to create an empty Array that you’ll fill completely, later on? new Array ( LEN )
- Do you need to create an Array initialized with a primitive value? new Array ( LEN ). fill ( 0 )
- Do you need to create an Array initialized with objects? Array . from ({ length : LEN }, () => ({}))
- Do you need to create a range of integers? Array . from ({ length : END - START }, ( x, i ) => i+ START )
If you are dealing with Arrays of integers or floats, consider Typed Arrays – which were created for this purpose. They can’t have holes and are always initialized with zeros.
Tip: Array performance usually doesn’t matter that much #
For most situations, I wouldn’t worry too much about performance. Even Arrays with holes are quite fast. It makes more sense to worry about your code being easy to understand.
Additionally, how and where engines optimize, changes. So what is fastest today, may not be tomorrow.
Acknowledgements #
- Thanks to Mathias Bynens and Benedikt Meurer for helping me get the V8 details right.
Further reading #
- Chapter “Arrays” in “JavaScript for impatient programmers”
- Chapter “Typed Arrays: handling binary data” in “JavaScript for impatient programmers”

- Stack Overflow Public questions & answers
- Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
- Talent Build your employer brand
- Advertising Reach developers & technologists worldwide
- About the company
Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Most efficient way to create a zero filled JavaScript array?
What is the most efficient way to create an arbitrary length zero filled array in JavaScript?
- 7 Some actual data on this: jsperf.com/zeroarrayjs – Web_Designer May 15, 2015 at 21:33
- 9 ES6 fill allows to do this natively. – Salvador Dali Sep 26, 2015 at 22:25
- 1 arr = new Array(length+1).joint(character).split(''); – Jordan Stefanelli Nov 29, 2015 at 19:05
- 5 UPDATE 2016 : Another custom benchmark here: jsfiddle.net/basickarl/md5z0Lqq – basickarl Jul 26, 2016 at 14:11
- 4 let i = 0; Array.from(Array(10), ()=>i++); – Bart Hoekstra Oct 3, 2017 at 20:51
45 Answers 45
ES6 introduces Array.prototype.fill . It can be used like this:
Not sure if it's fast, but I like it because it's short and self-describing.
It's still not in IE ( check compatibility ), but there's a polyfill available .
- 31 fill is fast. new Array(len) is painfully slow. (arr = []).length = len; arr.fill(0); is about the fastest solution ive seen anywhere... or at least tied – Pimp Trizkit Sep 22, 2015 at 16:08
- 11 @PimpTrizkit arr = Array(n) and (arr = []).length = n behave identically according to the spec. In some implementations one could be faster, but I don't think there is a big difference. – Oriol Sep 22, 2015 at 16:39
- 9 ... I will admit I missed this part ... when I add the second line to the test... arr.fill(0) ... everything sorta changes. Now, using new Array() is faster in most cases except when you get to array sizes > 100000... Then you can start to see the speed increase again. But if you don't actually have to prefill it with zeros and can use standard falisy of empty arrays. Then (arr = []).length = x is crazy fast in my test cases most of the time. – Pimp Trizkit Sep 23, 2015 at 0:15
- 7 Note that to iterate over the array (e.g. map or forEach) the values must be set , otherwise it will skip those indexes. The values you set can be whatever you want – even undefined. Example: try new Array(5).forEach(val => console.log('hi')); vs new Array(5).fill(undefined).forEach(val => console.log('hi')); . – ArneHugo Jun 2, 2016 at 11:03
- 4 I’m seeing fill() being quite a bit slower than a for loop when the array gets really big: jsperf.com/zero-filling-large-arrays And no significant difference between new Array(n) and a = []; a.length = n – swithinbank Nov 11, 2018 at 18:56
Although this is an old thread, I wanted to add my 2 cents to it. Not sure how slow/fast this is, but it's a quick one liner. Here is what I do:
If I want to pre-fill with a number:
If I want to pre-fill with a string:
Other answers have suggested:
but if you want 0 (the number) and not "0" (zero inside a string), you can do:
- 6 Great answer! Can you please explain the trick with Array.apply(null, new Array(5)).map(...) ? Cause simply doing (new Array(5)).map(...) won't work as the spec tells – Dmitry Pashkevich Jul 3, 2013 at 11:03
- 41 (btw, we don't really need the new ) When you do Array(5) you're creating an object that kinda looks like this: { length: 5, __proto__: Array.prototype } - try console.dir( Array(5) ) . Notice that it doesn't have any properties 0 , 1 , 2 , etc. But when you apply that unto the Array constructor, it's like saying Array(undefined, undefined, undefined, undefined, undefined) . And you get an object that kinda looks like { length: 5, 0: undefined, 1: undefined...} . map works on the properties 0 , 1 , etc. which is why your example doesn't work, but when you use apply it does. – zertosh Jul 3, 2013 at 15:58
- 5 The first parameter for .apply is actually what you want the this to be. For these purposes the this doesn't matter - we only really care about the parameter spreading "feature" of .apply - so it can be any value. I like null because it's cheap, you probably don't want to use {} or [] since you'd be instantiating an object for no reason. – zertosh Jul 4, 2013 at 0:15
- 2 Also initialize with size + assign is much faster than push. See test case jsperf.com/zero-fill-2d-array – Colin Apr 15, 2014 at 15:05
- 2 what about Array.apply(null, Array(5)).map(x=>0)? It's a little bit shorter! – ArchLinuxTux Mar 7, 2016 at 21:34
Fastest solution:
Shortest (handy) solution (3x slower for small arrays, slightly slower for big (slowest on Firefox))
Today 2020.06.09 I perform tests on macOS High Sierra 10.13.6 on browsers Chrome 83.0, Firefox 77.0, and Safari 13.1. I test chosen solutions for two test cases
- small array - with 10 elements - you can perform test HERE
- big arrays - with 1M elements - you can perform test HERE
Conclusions
- solution based on new Array(n)+for (N) is fastest solution for small arrays and big arrays (except Chrome but still very fast there) and it is recommended as fast cross-browser solution
- solution based on new Float32Array(n) (I) returns non typical array (e.g. you cannot call push(..) on it) so I not compare its results with other solutions - however this solution is about 10-20x faster than other solutions for big arrays on all browsers
- solutions based on for (L,M,N,O) are fast for small arrays
- solutions based on fill (B,C) are fast on Chrome and Safari but surprisingly slowest on Firefox for big arrays. They are medium fast for small arrays
- solution based on Array.apply (P) throws error for big arrays function P(n) { return Array.apply(null, Array(n)).map(Number.prototype.valueOf,0); } try { P(1000000); } catch(e) { console.error(e.message); }

Code and example
Below code presents solutions used in measurements
function A(n) { return [...new Array(n)].fill(0); } function B(n) { return new Array(n).fill(0); } function C(n) { return Array(n).fill(0); } function D(n) { return Array.from({length: n}, () => 0); } function E(n) { return [...new Array(n)].map(x => 0); } // arrays with type function F(n) { return Array.from(new Int32Array(n)); } function G(n) { return Array.from(new Float32Array(n)); } function H(n) { return Array.from(new Float64Array(n)); // needs 2x more memory than float32 } function I(n) { return new Float32Array(n); // this is not typical array } function J(n) { return [].slice.apply(new Float32Array(n)); } // Based on for function K(n) { let a = []; a.length = n; let i = 0; while (i < n) { a[i] = 0; i++; } return a; } function L(n) { let a=[]; for(let i=0; i<n; i++) a[i]=0; return a; } function M(n) { let a=[]; for(let i=0; i<n; i++) a.push(0); return a; } function N(n) { let a = new Array(n); for (let i=0; i<n; ++i) a[i] = 0; return a; } function O(n) { let a = new Array(n); for (let i=n; i--;) a[i] = 0; return a; } // other function P(n) { return Array.apply(null, Array(n)).map(Number.prototype.valueOf,0); } function Q(n) { return "0".repeat( n ).split("").map( parseFloat ); } function R(n) { return new Array(n+1).join('0').split('').map(parseFloat) } // --------- // TEST // --------- [A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R].forEach(f => { let a = f(10); console.log(`${f.name} length=${a.length}, arr[0]=${a[0]}, arr[9]=${a[9]}`) }); This snippets only present used codes
Example results for Chrome:

- Just ran some tests on Chrome 77 and a simple loop with push() is twice faster than fill()... I wonder what subtle side-effects of fill() prevent a more efficient implementation? – Eric Grange Oct 8, 2019 at 10:05
- @EricGrange I update answer - at the bottom I update link to benchamrk with your proposition: case P let a=[]; for(i=n;i--;) a.push(0); - but it is 4x slower than fill(0) - so I will even not update the picture witch that case. – Kamil Kiełczewski Oct 9, 2019 at 14:10
- 5 Nice measurements. Analysis: G is slow because of resizing the array at every iteration, and resizing means doing a new memory allocation. A,B,M fast because the sizing is done only once. +1 – Roland Mar 5, 2020 at 11:41
- 1 @Roland I think you mean N instead of M? – CyberMew Nov 7, 2020 at 14:20
- 2 for-loop (N) was only 1.835 faster than .fill (C) in Safari, and it's interesting to note that when I ran it now, 6 months later, the difference has gone down to only 1.456x. So for Safari, the fastest solution (N) is only 45% faster than the shortest and simplest version. Moral: Stick with the shortest and simplest versions (for most if not all cases). It saves expensive developer time, through being faster to read, easier to maintain, and also pays off more and more as time and CPU speeds increase, without extra maintenance. – Magne Dec 27, 2020 at 1:22
Elegant way to fill an array with precomputed values
Here is another way to do it using ES6 that nobody has mentioned so far:
It works by passing a map function as the second parameter of Array.from .
In the example above, the first parameter allocates an array of 3 positions filled with the value undefined and then the lambda function maps each one of them to the value 0 .
Although Array(len).fill(0) is shorter, it doesn't work if you need to fill the array by doing some computation first (I know the question didn't ask for it, but a lot of people end up here looking for this) .
For instance, if you need an array with 10 random numbers:
It's more concise (and elegant) than the equivalent:
This method can also be used to generate sequences of numbers by taking advantage of the index parameter provided in the callback:
Bonus answer: fill an array using String repeat()
Since this answer is getting a good deal of attention, I also wanted to show this cool trick. Although not as useful as my main answer, will introduce the still not very known, but very useful String repeat() method. Here's the trick:
Cool, huh? repeat() is a very useful method to create a string that is the repetition of the original string a certain number of times. After that, split() creates an array for us, which is then map() ped to the values we want. Breaking it down in steps:
- Lots of parlor tricks in that post, but hopefully none that will reach production code :) – Eric Grange Oct 8, 2019 at 10:01
- 1 Although the repeat trick is definitely not wanted in production, Array.from() is perfectly fine :-) – Lucio Paiva Oct 14, 2019 at 0:27
- Not really, Array.from() here is basically creating an array, iterating through it with map(), calling a function on each item to create a new array, then discarding the first array... For a small arrays this may be innocuous, for larger arrays, this is the kind of pattern that result in people calling browsers "memory hogs" :) – Eric Grange Oct 15, 2019 at 9:07
- People dealing with large arrays should know better than this, definitely. For common apps, though, creating a regular-sized aux array (up to 10k elements) that will be immediately disposed is perfectly fine (takes the same amount of time as if you avoided the extra array creation - tested with latest Chrome). For cases like that, readability becomes more important than tiny performance optimizations. About the O(n) time, it's necessary if you need to compute something different for each element (the main subject of my answer). This discussion is very interesting, glad that you raised it! – Lucio Paiva Oct 15, 2019 at 15:00
- ^ To clarify for future readers: the above comments imply that Array(N) pre-allocates N cells, which isn't necessarily true, otherwise Array(2**32 - 1) would be allocating more than all my RAM. Browser engines likely use various heuristics to determine whether or not to allocate in advance or use a sparse array. In any case, you can use Array.from({ length: N }, callback) instead. – Domino Oct 21, 2022 at 9:40
The already mentioned ES 6 fill method takes care of this nicely. Most modern desktop browsers already support the required Array prototype methods as of today (Chromium, FF, Edge and Safari) [ 1 ]. You can look up details on MDN . A simple usage example is
Given the current browser support you should be cautious to use this unless you are sure your audience uses modern Desktop browsers.
- 5 If you fill with a reference type it will be the same reference across all of them. new Array(10).fill(null).map(() => []) would be a succinct way to get around this (burned me initially haha) – John Culviner Feb 17, 2016 at 18:17
- 4 UPDATE 2016 : This method blows everything else out of the water, click here for benchmarks: jsfiddle.net/basickarl/md5z0Lqq – basickarl Jul 26, 2016 at 14:09
- this will work for arrays. a = Array(10).fill(null).map(() => { return []; }); – Andrew Aug 7, 2016 at 17:54
- 2 @AndrewAnthonyGerst Terser: a = Array(10).fill(0).map( _ => [] ); – Phrogz Jul 22, 2017 at 5:16
Note added August 2013, updated February 2015: The answer below from 2009 relates to JavaScript's generic Array type. It doesn't relate to the newer typed arrays defined in ES2015 [and available now in many browsers], like Int32Array and such. Also note that ES2015 adds a fill method to both Arrays and typed arrays , which is likely to be the most efficient way to fill them...
Also, it can make a big difference to some implementations how you create the array. Chrome's V8 engine, in particular, tries to use a highly-efficient, contiguous-memory array if it thinks it can, shifting to the object-based array only when necessary.
With most languages, it would be pre-allocate, then zero-fill, like this:
But , JavaScript arrays aren't really arrays , they're key/value maps just like all other JavaScript objects, so there's no "pre-allocate" to do (setting the length doesn't allocate that many slots to fill), nor is there any reason to believe that the benefit of counting down to zero (which is just to make the comparison in the loop fast) isn't outweighed by adding the keys in reverse order when the implementation may well have optimized their handling of the keys related to arrays on the theory you'll generally do them in order.
In fact, Matthew Crumley pointed out that counting down is markedly slower on Firefox than counting up, a result I can confirm — it's the array part of it (looping down to zero is still faster than looping up to a limit in a var). Apparently adding the elements to the array in reverse order is a slow op on Firefox. In fact, the results vary quite a bit by JavaScript implementation (which isn't all that surprising). Here's a quick and dirty test page (below) for browser implementations (very dirty, doesn't yield during tests, so provides minimal feedback and will run afoul of script time limits). I recommend refreshing between tests; FF (at least) slows down on repeated tests if you don't.
The fairly complicated version that uses Array#concat is faster than a straight init on FF as of somewhere between 1,000 and 2,000 element arrays. On Chrome's V8 engine, though, straight init wins out every time...
Here's a test:
const tests = [ { name: "downpre", total: 0, desc: "Count down, pre-decrement", func: makeWithCountDownPre }, { name: "downpost", total: 0, desc: "Count down, post-decrement", func: makeWithCountDownPost }, { name: "up", total: 0, desc: "Count up (normal)", func: makeWithCountUp }, { name: "downandup", total: 0, desc: "Count down (for loop) and up (for filling)", func: makeWithCountDownArrayUp }, { name: "concat", total: 0, desc: "Concat", func: makeWithConcat } ]; const q = sel => document.querySelector(sel); let markup = ""; for (const {name, desc} of tests) { markup += ` <div><input type="checkbox" id="chk_${name}" checked> <label for="chk_${name}">${desc}</label></div>`; } q("#checkboxes").innerHTML = markup; q("#btnTest").addEventListener("click", btnTestClick); function btnTestClick() { // Clear log q("#log").innerHTML = "Testing..."; // Show running q("#btnTest").disabled = true; // Run after a pause while the browser updates display setTimeout(btnTestClickPart2, 0); } function btnTestClickPart2() { try { runTests(); } catch (e) { log(`Exception: ${e.message}`); } // Re-enable the button q("#btnTest").disabled = false; } function getNumField(name) { const val = q("#" + name).value.trim(); const num = /^\d+$/.test(val) ? parseInt(val) : NaN; if (isNaN(num) || num <= 0) { throw new Error(`Invalid ${name} value ${JSON.stringify(val)}`); } return num; } function runTests() { try { // Clear log q("#log").innerHTML = ""; const runCount = getNumField("loops"); const length = getNumField("length"); // Do it (we run runCount + 1 times, first time is a warm up) for (let counter = 0; counter <= runCount; ++counter) { for (const test of tests) { if (q("#chk_" + test.name).checked) { const start = Date.now(); const a = test.func(length); const time = Date.now() - start; if (counter == 0) { // Don't count (warm up), but do check the algorithm works const invalid = validateResult(a, length); if (invalid) { log(`<span class=error>FAILURE</span> with test ${test.name}: ${invalid}`); return; } } else { // Count this one log(`#${counter}: ${test.desc}: ${time}ms`); test.total += time; } } } } for (const test of tests) { if (q("#chk_" + test.name).checked) { test.avg = test.total / runCount; if (typeof lowest != "number" || lowest > test.avg) { lowest = test.avg; } } } let results = "<p>Results:" + "<br>Length: " + length + "<br>Loops: " + runCount + "</p>"; for (const test of tests) { if (q("#chk_" + test.name).checked) { results += `<p ${lowest == test.avg ? " class=winner" : ""}>${test.desc}, average time: ${test.avg}ms</p>`; } } results += "<hr>"; q("#log").insertAdjacentHTML("afterbegin", results); } catch (e) { log(e.message); return; } } function validateResult(a, length) { if (a.length != length) { return "Length is wrong"; } for (let n = length - 1; n >= 0; --n) { if (a[n] != 0) { return "Index " + n + " is not zero"; } } return undefined; } function makeWithCountDownPre(len) { const a = new Array(len); while (--len >= 0) { a[len] = 0; } return a; } function makeWithCountDownPost(len) { const a = new Array(len); while (len-- > 0) { a[len] = 0; } return a; } function makeWithCountUp(len) { const a = new Array(len); for (let i = 0; i < len; ++i) { a[i] = 0; } return a; } function makeWithCountDownArrayUp(len) { const a = new Array(len); let i = 0; while (--len >= 0) { a[i++] = 0; } return a; } function makeWithConcat(len) { if (len == 0) { return []; } let a = [0]; let currlen = 1; while (currlen < len) { const rem = len - currlen; if (rem < currlen) { a = a.concat(a.slice(0, rem)); } else { a = a.concat(a); } currlen = a.length; } return a; } function log(msg) { const p = document.createElement("p"); p.textContent = msg; q("#log").appendChild(p); } body { font-family: sans-serif; } #log p { margin: 0; padding: 0; } .error { color: red; } .winner { color: green; } <div> <label for='txtLength'>Length:</label><input type='text' id='length' value='1000'> <br><label for='txtLoops'>Loops:</label><input type='text' id='loops' value='100000'> <div id='checkboxes'></div> <br><input type='button' id='btnTest' value='Test'> <hr> <div id='log'></div> </div>

- Not sure that backwards filling would matter here, given you are only accessing elements (not deleting them) and you've already pre-allocated. Am I wrong? – Kenan Banks Aug 18, 2009 at 20:52
- the point of the backwards fill is not particularly to do with the array, it's to do with the escape condition for the while - the falsey 0 terminates the loop very efficiently – annakata Aug 18, 2009 at 20:54
- (though I've just noticed this code doesn't actually make use of that) – annakata Aug 18, 2009 at 20:56
- @annakata, you can't make use of that here, because 0 is a valid index. – Kenan Banks Aug 18, 2009 at 20:59
- @triptych: not true, all it takes is the right order - see my post – annakata Aug 18, 2009 at 21:05
If you use ES6, you can use Array.from() like this:
Has the same result as
By default Uint8Array , Uint16Array and Uint32Array classes keep zeros as its values, so you don't need any complex filling techniques, just do:
all elements of array ary will be zeros by default.
- 5 This is nice but mind note this cannot be treated the same as a normal array, e.g. Array.isArray(ary) is false . The length is also read-only so you cannot push new items to it as with ary.push – MusikAnimal Jan 14, 2017 at 2:22
- Fwiw all typed arrays keep 0 as their default value. – jfunk May 2, 2017 at 2:55
- 3 @MusikAnimal, Array.from(new Uint8Array(10)) will provide a normal array. – Tomas Langkaas Jun 23, 2017 at 14:31
- @TomasLangkaas: Yes, but another answer shows that that's about 5x slower than Array(n).fill(0) in Chrome if what you really need is a JS Array. If you can use a TypedArray, this is much faster even than .fill(0) , though, especially if you can use the default initializer value of 0 . There doesn't seem to be a constructor that takes a fill-value and length, the way C++ std::vector has. It seems for any non-zero value you have to construct a zeroed TypedArray and then fill it. :/ – Peter Cordes Nov 20, 2019 at 7:22
Note that while is usually more efficient than for-in , forEach , etc.
- 4 Isn't the i local variable extraneous? length is passed by value so you should be able to decrement it directly. – Sean Bright Aug 18, 2009 at 18:26
- 3 Although this looks great at first, unfortunately it's very slow to assign values at an arbitrary point in an arary (e.g. arr[i] = value ). It's much faster to loop through from beginning to end and use arr.push(value) . It's annoying, because I prefer your method. – Nick Brunt Jul 26, 2014 at 15:13
using object notation
zero filled? like...
filled with 'undefined'...
obj notation with zeros
As a side note, if you modify Array's prototype, both
will have those prototype modifications
At any rate, I wouldn't be overly concerned with the efficiency or speed of this operation, there are plenty of other things that you will likely be doing that are far more wasteful and expensive than instanciating an array of arbitrary length containing zeros.

- 5 Err... there are no null s in this array - var x = new Array(7); – kangax Aug 18, 2009 at 18:25
- 5 Actually, the array doesn't get filled with anything with new Array(n), not even 'undefined's, it simply sets the arrays length value to n. You can check this by calling (new Array(1)).forEach(...). forEach never executes, unlike if you call it on [undefined]. – JussiR Sep 19, 2013 at 15:03
- 7 new Array(7) does not create an array "filled with undefined". It creates an empty array with length 7. – RobG Dec 17, 2014 at 23:06
- 2 You might want to reconsider parts of your answer as what @RobG is saying is critical (if what you were saying is true, mapping would have been much easier) – Abdo Aug 6, 2015 at 10:06
- 1 These days you could do (new Array(10)).fill(0) . – Javier de la Rosa Feb 16, 2018 at 21:17
I've tested all combinations of pre-allocating/not pre-allocating, counting up/down, and for/while loops in IE 6/7/8, Firefox 3.5, Chrome, and Opera.
The functions below was consistently the fastest or extremely close in Firefox, Chrome, and IE8, and not much slower than the fastest in Opera and IE 6. It's also the simplest and clearest in my opinion. I've found several browsers where the while loop version is slightly faster, so I'm including it too for reference.
- 1 You could also throw the var array = [] declaration into the first part of the for loop actually, separated by only a comma. – damianb Nov 19, 2012 at 14:51
- I like that suggestion by damianb, but remember to put the assignment and comma before the incrementation! `for (var i = 0; i < length; array[i] = val, i++); – punstress Mar 15, 2015 at 1:39
- Do what everyone else is missing to your second one, and set the length of the array to the length value already given so that it's not constantly changing. Brought a 1 million length array of zero's from 40ms to 8 on my machine. – Jonathan Gray Sep 7, 2015 at 7:49
- I seem to get a 10-15% speed increase when I refactor this solution into a one liner. for (i = 0, array = []; i < length; ++i) array[i] = val; .. Fewer blocks? ... anyhow, also... if I set the array.length of the new array to the length.. i seem to get another 10%-15% speed increase in FF... in Chrome, it seems to double the speed -> var i, array = []; array.length = length; while(i < length) array[i++] = val; (was still faster if I left it as a for loop... but the init is no longer needed, so the while is seemly faster on this version) – Pimp Trizkit Sep 22, 2015 at 23:11
- I will also note that in my testing. In a decent number of my test cases, the final version above seems to perform 3x to well over 10x faster... Im not so sure why... (different array sizes tested between chrome and FF) – Pimp Trizkit Sep 22, 2015 at 23:23
ES6 solution:

const arr = Array.from({ length: 10 }).fill(0); console.log(arr)

If you need to create many zero filled arrays of different lengths during the execution of your code, the fastest way I've found to achieve this is to create a zero array once , using one of the methods mentioned on this topic, of a length which you know will never be exceeded, and then slice that array as necessary.
For example (using the function from the chosen answer above to initialize the array), create a zero filled array of length maxLength , as a variable visible to the code that needs zero arrays:
Now slice this array everytime you need a zero filled array of length requiredLength < maxLength :
I was creating zero filled arrays thousands of times during execution of my code, this speeded up the process tremendously.
- 3 You might also use new Array(size+1).join("x").split("x").map(function() { return 0; }) to get actual numbers – Yuval Apr 6, 2012 at 23:27
- 6 @Yuval Or just new Array(size+1).join('0').split('').map(Number) – Paul Jan 13, 2014 at 17:25
Using lodash or underscore
Or if you have an array existing and you want an array of the same length
- So glad you added this answer, as I use underscore, and I knew there was something for this... but hadn't been able to find it yet. I just wish I could create arrays of objects using this – PandaWood Oct 22, 2014 at 6:02
- @PandaWood _.range(0, length -1, 0).map(Object.new), I think. – djechlin Oct 22, 2014 at 11:51
- Should be _.range(0, length, 0) , I believe. Lodash is exclusive of end value – user4815162342 Jun 25, 2016 at 21:26
I have nothing against:
suggested by Zertosh, but in a 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:
which gives you: [1, 2, 3, 9, 9, 6]
To create an all new Array
To add some values at the end of an existing Array
[...existingArray, ...new Array(numberOfElementsToAdd).fill(0)]
//**To create an all new Array** console.log(new Array(5).fill(0)); //**To add some values at the end of an existing Array** let existingArray = [1,2,3] console.log([...existingArray, ...new Array(5).fill(0)]);
The way I usually do it (and is amazing fast) is using Uint8Array . For example, creating a zero filled vector of 1M elements:
I'm a Linux user and always have worked for me, but once a friend using a Mac had some non-zero elements. I thought his machine was malfunctioning, but still here's the safest way we found to fix it:
Chrome 25.0.1364.160
- Frederik Gottlieb - 6.43
- Sam Barnum - 4.83
- Joshua 2.91
- Mathew Crumley - 2.67
- bduran - 2.55
- Allen Rice - 2.11
- kangax - 0.68
- Tj. Crowder - 0.67
- zertosh - ERROR
Firefox 20.0
- Allen Rice - 1.85
- Joshua - 1.82
- Mathew Crumley - 1.79
- bduran - 1.37
- Frederik Gottlieb - 0.67
- Sam Barnum - 0.63
- kagax - 0.13
- Tj. Crowder - 0.13
Missing the most important test (at least for me): the Node.js one. I suspect it close to Chrome benchmark.

- This is the most efficient way for my fingers, and for my eyes. But it's very very slow for Chrome (accord to that jsperf. 99% slower). – Orwellophile Mar 5, 2016 at 5:20
- 1 I wonder if the problem on your friend's Mac was related to: stackoverflow.com/questions/39129200/… or maybe Array.slice wasn't handling the UInt8Array and leaking uninitialised memory? (a security issue!). – robocat Aug 31, 2017 at 5:04
- @robocat Good catch! If I remember it well we were using Node.js 0.6 or 0.8. We thought about some kind of leaking but we could not reproduce it with the production stack so we just decided to ignore it. – durum Sep 4, 2017 at 9:48
As of ECMAScript2016 , there is one clear choice for large arrays.
Since this answer still shows up near the top on google searches, here's an answer for 2017.
Here's a current jsbench with a few dozen popular methods, including many proposed up to now on this question. If you find a better method please add, fork and share.
I want to note that there is no true most efficient way to create an arbitrary length zero filled array. You can optimize for speed, or for clarity and maintainability - either can be considered the more efficient choice depending on the needs of the project.
When optimizing for speed, you want to: create the array using literal syntax; set the length, initialize iterating variable, and iterate through the array using a while loop. Here's an example.
const arr = []; arr.length = 120000; let i = 0; while (i < 120000) { arr[i] = 0; i++; }
Another possible implementation would be:
But I strongly discourage using this second implantation in practice as it's less clear and doesn't allow you to maintain block scoping on your array variable.
These are significantly faster than filling with a for loop, and about 90% faster than the standard method of
But this fill method is still the most efficient choice for smaller arrays due to it's clarity, conciseness and maintainability. The performance difference likely won't kill you unless you're making a lot of arrays with lengths on the order of thousands or more.
A few other important notes. Most style guides recommend you no longer use var without a very special reason when using ES6 or later. Use const for variables that won't be redefined and let for variables that will. The MDN and Airbnb's Style Guide are great places to go for more information on best practices. The questions wasn't about syntax, but it's important that people new to JS know about these new standards when searching through these reams of old and new answers.

Didn't see this method in answers, so here it is:
In result you will get zero-valued array of length 200:
I'm not sure about the performance of this code, but it shouldn't be an issue if you use it for relatively small arrays.
- 6 Neither the fastest nor the shortest but a nice contribution to the diversity of solutions. – 7vujy0f0hy Apr 19, 2017 at 13:42
What about new Array(51).join('0').split('') ?

- 1 then .map(function(a){return +a}) ? – lonewarrior556 Jun 10, 2016 at 13:32
- as for 2020, what about new Array(51).fill(0) ? It gives exact the same output. – phen0menon Oct 19, 2020 at 13:36
- "0".repeat(100000000).split(''); significantly faster than all others. – Ali Mar 21, 2022 at 4:14
let filled = []; filled.length = 10; filled.fill(0); console.log(filled);
This concat version is much faster in my tests on Chrome (2013-03-21). About 200ms for 10,000,000 elements vs 675 for straight init.
Bonus: if you want to fill your array with Strings, this is a concise way to do it (not quite as fast as concat though):
- 2 Ok, wild. That is WAY faster than using new Array(len). BUT! I am seeing in Chrome that the subsequent reads to that data take substantially longer. Here are some timestamps to show what I mean: (Using new Array(len)) 0.365: Making Array 4.526: Executing Convolution 10.75: Convolution Complete (Using concat) 0.339: Making Array 0.591: Executing Convolution //OMG, WAY faster 18.056: Convolution Complete – Brooks May 1, 2013 at 17:06
I was testing out the great answer by T.J. Crowder, and came up with a recursive merge based on the concat solution that outperforms any in his tests in Chrome (i didn't test other browsers).
call the method with makeRec(29) .
It might be worth pointing out, that Array.prototype.fill had been added as part of the ECMAScript 6 (Harmony) proposal . I would rather go with the polyfill written below, before considering other options mentioned on the thread.
Shortest for loop code
Safe var version
- 2 Given that the length is a defined variable, n , this would be shorter: for(var a=[];n--;a[n]=0); – Tomas Langkaas Dec 8, 2016 at 12:49
My fastest function would be:
Using the native push and shift to add items to the array is much faster (about 10 times) than declaring the array scope and referencing each item to set it's value.
fyi: I consistently get faster times with the first loop, which is counting down, when running this in firebug (firefox extension).
I'm interested to know what T.J. Crowder makes of that ? :-)
- You can make it faster by changing it to while (len--) .. took my processing times from about 60ms to about 54ms – nickf Aug 21, 2009 at 8:23
- Matthew Crumbly's answer still actually beats this (30ms)! – nickf Aug 21, 2009 at 8:31
I knew I had this proto'd somewhere :)
Edit: tests
In response to Joshua and others methods I ran my own benchmarking, and I'm seeing completely different results to those reported.
Here's what I tested:
So by my reckoning push is indeed slower generally but performs better with longer arrays in FF but worse in IE which just sucks in general (quel surprise).
- I've just tested this out: the second method ( b = []... ) is 10-15% faster than the first, but it's more than 10 times slower than Joshua's answer. – nickf Aug 21, 2009 at 8:27
- I know this is an ancient post . But maybe it is still of interest to others (like me). Therefore I would like to suggest an adition to the prototype function: include an else {this.length=n;} after the this.length -check. This will shorten an already existing array if necessary when re- init -ialising it to a different length n . – Carsten Massmann Aug 25, 2015 at 7:42
Anonymous function:
A bit shorter with for-loop:
Works with any Object , just change what's inside this.push() .
You can even save the function:
Call it using:
Adding elements to an already existing array:
Performance: http://jsperf.com/zero-filled-array-creation/25

- '0 '.repeat(200).split(' ') – Hank W May 31, 2021 at 3:27
Not the answer you're looking for? Browse other questions tagged javascript arrays or ask your own question .
- The Overflow Blog
- Five Stack Exchange sites turned ten years old this quarter!
- “Move fast and break things” doesn’t apply to other people’s savings (Ep. 544)
- Featured on Meta
- We've added a "Necessary cookies only" option to the cookie consent popup
- Launching the CI/CD and R Collectives and community editing features for...
- The [amazon] tag is being burninated
- Temporary policy: ChatGPT is banned
- Staging Ground Beta 1 Recap, and Reviewers needed for Beta 2
Hot Network Questions
- Does Hooke's Law apply to all springs?
- Is there any room for negotiation on my PhD program stipend offers?
- Overcurrent protection (at 4A 100V)
- Why is the work done by the tension in a pendulum string 0?
- In England, why are some high schools called hospitals?
- One-day-ahead prediction of S&P500 with Temporal Convolutional Networks
- Max-heap implementation in C
- Was Kip's defiance relevant to the Galactics' decision?
- What would be the advantage of launching an UN-led inquiry over the Nord Stream sabotage?
- Distrust versus mistrust
- How do/should administrators estimate the cost of producing an online introductory mathematics class?
- How deep underground could a city plausably be?
- Ash - Complex Variables - Proof of Maximum Principle
- Is Grogu the same species as Yoda?
- Imtiaz Germain Primes
- How do you ensure that a red herring doesn't violate Chekhov's gun?
- Do Catholic anathemas apply to people who lived before it was codified?
- Concrete base for parcel box
- A Swiss watch company seized my watch, saying it was stolen. I bought it 10 years ago. Is that legal?
- Are there any medieval manuals relating to castle building?
- Gunslinger Fake Out with Covered Reload
- Mando's Mandatory Meandering?
- What is the name of the color used by the SBB (Swiss Federal Railway) in the 1920s to paint their locomotive?
- How do PCB Trace Width Calculators work? And why is it asking me to input the width of it?
Your privacy
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .

How to Fill an Array with Initial Values in JavaScript
JavaScript provides many ways to initialize arrays with initial data. Let's see in this post which ways are the most simple and popular.
Before I go on, let me recommend something to you.
If you want to significantly improve your JavaScript knowledge, take the amazingly useful course "Modern JavaScript From The Beginning 2.0" by Brad Traversy. Use the coupon code "DMITRI" and get up to 20% discount!
Table of Contents
1. fill an array with primitives, 2.1 using array.fill(), 2.2 using array.from(), 2.3 using array.map() with spread operator, 3. conclusion.
Let's say that you'd like to initialize an array of length 3 with zeros.
The array.fill(initalValue) method available on the array instance is a convenient way to initialize an arrays: when the method is called on an array, the entire array is filled with initialValue , and the modified array is returned.
But you need to use array.fill(initialValue) in combination with Array(n) (the array constructor):
Try the demo.
Array(length) creates a sparse array with the length of 3 .
Then Array(length).fill(0) method fills the array with zeroes, returning the filled array: [0, 0, 0] .
Array(length).fill(initialValue) is a convenient way to create arrays with a desired length and initialized with a primitive value (number, string, boolean).
2. Fill an array with objects
What if you need to fill an array with objects? This requirement is slightly nuanced depending if you want the array filled with the initial object instances, or different instances.
If you don't mind initializing the array with the same object instance, then you could easily use array.fill() method mentioned above:
Array(length).fill({ value: 0 }) creates an array of length 3 , and assigns to each item the { value: 0 } (note: same object instance).
This approach creates an array having the same object instance. If you happen to modify any item in the array, then each item in the array is affected:
Altering the second item of the array filledArray[1].value = 3 alters all the items in the array.
In case if you want the array to fill with copies of the initial object, then you could use the Array.from() utility function.
Array.from(array, mapperFunction) accepts 2 arguments: an array (or generally an iterable), and a mapper function.
Array.from() invokes the mapperFunction upon each item of the array, pushes the result to a new array, and finally returns the newly mapped array.
Thus Array.from() method can easily create and initialize an array with different object instances:
Array.from() invokes the mapper function on each empty slot of the array and creates a new array with every value returned from the mapper function.
You get a filled array with different object instances because each mapper function call returns a new object instance.
If you'd modify any item in the array, then only that item would be affected, and the other ones remain unaffected:
filledArray[1].value = 3 modifies only the second item of the array.
You may be wondering: why use Array.from() and its mapper function, since the array has already an array.map() method?
Good question!
When using Array(length) to create array instances, it creates sparse arrays (i.e. with empty slots):
And the problem is that array.map() skips the empty slots:
Thus using directly Array(length).map(mapperFunc) would create sparse arrays.
Fortunately, you can use the spread operator to transform a sparse array into an array with items initialized with undefined . Then apply array.map() method on that array:
The expression [...Array(length)] creates an array with items initialized as undefined . On such an array, array.map() can map to new object instances.
I prefer the Array.from() approach to filling an array with objects because it involves less magic.
JavaScript provides a bunch of good ways to fill an array with initial values.
If you'd like to create an array initialized with primitive values, then the best approach is Array(length).fill(initialValue) .
To create an array initialized with object instances, and you don't care that each item would have the same object instance, then Array(length).fill(initialObject) is the way to go.
Otherwise, to fill an array with different object instances you could use Array.from(Array.length, mapper) or [...Array(length)].map(mapper) , where mapper is a function that returns a new object instance on each call.
What other ways to fill an array in JavaScript do you know?
Like the post? Please share!
Quality posts into your inbox.
I regularly publish posts containing:
- Important JavaScript concepts explained in simple words
- Overview of new JavaScript features
- How to use TypeScript and typing
- Software design and good coding practices
Subscribe to my newsletter to get them right into your inbox.

About Dmitri Pavlutin
Recommended reading:, 5 handy applications of javascript array.from(), 15 common operations on arrays in javascript (cheatsheet), popular posts.
- Skip to main content
- Skip to search
- Skip to select language
- Get MDN Plus
- English (US)
Array: length
The length data property of an Array instance represents the number of elements in that array. The value is an unsigned, 32-bit integer that is always numerically greater than the highest index in the array.
A non-negative integer less than 2 32 .
Description
The value of the length property is a non-negative integer with a value less than 2 32 .
The array object observes the length property, and automatically syncs the length value with the array's content. This means:
- Setting length to a value smaller than the current length truncates the array — elements beyond the new length are deleted.
- Setting any array index (a non-negative integer smaller than 2 32 ) beyond the current length extends the array — the length property is increased to reflect the new highest index.
- Setting length to an invalid value (e.g. a negative number or a non-integer) throws a RangeError exception.
When length is set to a bigger value than the current length, the array is extended by adding empty slots , not actual undefined values. Empty slots have some special interactions with array methods; see array methods and empty slots .
See also Relationship between length and numerical properties .
Iterating over an array
In the following example, the array numbers is iterated through by looking at the length property. The value in each element is then doubled.
Shortening an array
The following example shortens the array numbers to a length of 3 if the current length is greater than 3.
Create empty array of fixed length
Setting length to a value greater than the current length creates a sparse array .
Array with non-writable length
The length property is automatically updated by the array when elements are added beyond the current length. If the length property is made non-writable, the array will not be able to update it. This causes an error in strict mode .
Specifications
Browser compatibility.
BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
- RangeError: invalid array length
- Data Structure & Algorithm Classes (Live)
- System Design (Live)
- DevOps(Live)
- Explore More Live Courses
- Interview Preparation Course
- Data Science (Live)
- GATE CS & IT 2024
- Data Structure & Algorithm-Self Paced(C++/JAVA)
- Data Structures & Algorithms in Python
- Explore More Self-Paced Courses
- C++ Programming - Beginner to Advanced
- Java Programming - Beginner to Advanced
- C Programming - Beginner to Advanced
- Full Stack Development with React & Node JS(Live)
- Java Backend Development(Live)
- Android App Development with Kotlin(Live)
- Python Backend Development with Django(Live)
- Complete Data Science Program(Live)
- Mastering Data Analytics
- DevOps Engineering - Planning to Production
- CBSE Class 12 Computer Science
- School Guide
- All Courses
- Linked List
- Binary Tree
- Binary Search Tree
- Advanced Data Structure
- All Data Structures
- Asymptotic Analysis
- Worst, Average and Best Cases
- Asymptotic Notations
- Little o and little omega notations
- Lower and Upper Bound Theory
- Analysis of Loops
- Solving Recurrences
- Amortized Analysis
- What does 'Space Complexity' mean ?
- Pseudo-polynomial Algorithms
- Polynomial Time Approximation Scheme
- A Time Complexity Question
- Searching Algorithms
- Sorting Algorithms
- Graph Algorithms
- Pattern Searching
- Geometric Algorithms
- Mathematical
- Bitwise Algorithms
- Randomized Algorithms
- Greedy Algorithms
- Dynamic Programming
- Divide and Conquer
- Backtracking
- Branch and Bound
- All Algorithms
- Company Preparation
- Practice Company Questions
- Interview Experiences
- Experienced Interviews
- Internship Interviews
- Competitive Programming
- Design Patterns
- System Design Tutorial
- Multiple Choice Quizzes
- Go Language
- Tailwind CSS
- Foundation CSS
- Materialize CSS
- Semantic UI
- Angular PrimeNG
- Angular ngx Bootstrap
- jQuery Mobile
- jQuery EasyUI
- React Bootstrap
- React Rebass
- React Desktop
- React Suite
- ReactJS Evergreen
- ReactJS Reactstrap
- BlueprintJS
- TensorFlow.js
- English Grammar
- School Programming
- Number System
- Trigonometry
- Probability
- Mensuration
- Class 8 Syllabus
- Class 9 Syllabus
- Class 10 Syllabus
- Class 11 Syllabus
- Class 8 Notes
- Class 9 Notes
- Class 10 Notes
- Class 11 Notes
- Class 12 Notes
- Class 8 Formulas
- Class 9 Formulas
- Class 10 Formulas
- Class 11 Formulas
- Class 8 Maths Solution
- Class 9 Maths Solution
- Class 10 Maths Solution
- Class 11 Maths Solution
- Class 12 Maths Solution
- Class 7 Notes
- History Class 7
- History Class 8
- History Class 9
- Geo. Class 7
- Geo. Class 8
- Geo. Class 9
- Civics Class 7
- Civics Class 8
- Business Studies (Class 11th)
- Microeconomics (Class 11th)
- Statistics for Economics (Class 11th)
- Business Studies (Class 12th)
- Accountancy (Class 12th)
- Macroeconomics (Class 12th)
- Machine Learning
- Data Science
- Mathematics
- Operating System
- Computer Networks
- Computer Organization and Architecture
- Theory of Computation
- Compiler Design
- Digital Logic
- Software Engineering
- GATE 2024 Live Course
- GATE Computer Science Notes
- Last Minute Notes
- GATE CS Solved Papers
- GATE CS Original Papers and Official Keys
- GATE CS 2023 Syllabus
- Important Topics for GATE CS
- GATE 2023 Important Dates
- Software Design Patterns
- HTML Cheat Sheet
- CSS Cheat Sheet
- Bootstrap Cheat Sheet
- JS Cheat Sheet
- jQuery Cheat Sheet
- Angular Cheat Sheet
- Facebook SDE Sheet
- Amazon SDE Sheet
- Apple SDE Sheet
- Netflix SDE Sheet
- Google SDE Sheet
- Wipro Coding Sheet
- Infosys Coding Sheet
- TCS Coding Sheet
- Cognizant Coding Sheet
- HCL Coding Sheet
- FAANG Coding Sheet
- Love Babbar Sheet
- Mass Recruiter Sheet
- Product-Based Coding Sheet
- Company-Wise Preparation Sheet
- Array Sheet
- String Sheet
- Graph Sheet
- ISRO CS Original Papers and Official Keys
- ISRO CS Solved Papers
- ISRO CS Syllabus for Scientist/Engineer Exam
- UGC NET CS Notes Paper II
- UGC NET CS Notes Paper III
- UGC NET CS Solved Papers
- Campus Ambassador Program
- School Ambassador Program
- Geek of the Month
- Campus Geek of the Month
- Placement Course
- Testimonials
- Student Chapter
- Geek on the Top
- Geography Notes
- History Notes
- Science & Tech. Notes
- Ethics Notes
- Polity Notes
- Economics Notes
- UPSC Previous Year Papers
- SSC CGL Syllabus
- General Studies
- Subjectwise Practice Papers
- Previous Year Papers
- SBI Clerk Syllabus
- General Awareness
- Quantitative Aptitude
- Reasoning Ability
- SBI Clerk Practice Papers
- SBI PO Syllabus
- SBI PO Practice Papers
- IBPS PO 2022 Syllabus
- English Notes
- Reasoning Notes
- Mock Question Papers
- IBPS Clerk Syllabus
- Apply for a Job
- Apply through Jobathon
- Hire through Jobathon
- All DSA Problems
- Problem of the Day
- GFG SDE Sheet
- Top 50 Array Problems
- Top 50 String Problems
- Top 50 Tree Problems
- Top 50 Graph Problems
- Top 50 DP Problems
- Solving For India-Hackthon
- GFG Weekly Coding Contest
- Job-A-Thon: Hiring Challenge
- BiWizard School Contest
- All Contests and Events
- Saved Videos
- What's New ?
- JS-Function
- JS-Generator
- JS-Expressions
- JS-ArrayBuffer
- JS-Tutorial
- Web Development
- Web-Technology
Related Articles
- Write Articles
- Pick Topics to write
- Guidelines to Write
- Get Technical Writing Internship
- Write an Interview Experience
- How to calculate the number of days between two dates in JavaScript ?
- File uploading in React.js
- Hide elements in HTML using display property
- How to append HTML code to a div using JavaScript ?
- Difference between var and let in JavaScript
- JavaScript Number toString() Method
- Convert a string to an integer in JavaScript
- How to Open URL in New Tab using JavaScript ?
- How do you run JavaScript script through the Terminal?
- JavaScript console.log() Method
- How to read a local text file using JavaScript?
- Differences between Functional Components and Class Components in React
- Difference between TypeScript and JavaScript
- Form validation using HTML and JavaScript
- HTML Calculator
- Node.js | fs.writeFileSync() Method
- How to add an object to an array in JavaScript ?
- How to Use the JavaScript Fetch API to Get Data?
- How to get value of selected radio button using JavaScript ?
- How to convert Set to Array in JavaScript ?
- How to force Input field to enter numbers only using JavaScript ?
- Remove elements from a JavaScript Array
- Set the value of an input field in JavaScript
- How to create an image element dynamically using JavaScript ?
- Create a Responsive Navbar using ReactJS
- Check if an array is empty or not in JavaScript
- How to remove a character from string in JavaScript ?
- How to compare two arrays in JavaScript ?
- How to filter object array based on attributes?
- Difference between var, let and const keywords in JavaScript
Create an array of given size in JavaScript
- Last Updated : 05 Jan, 2023
Creating an array of a given size can be implemented in many ways, and each way is useful in some conditions. We will explain each possible ways to create an array with the given size with a proper example.
Method 1: In this method, we use the JavaScript Array constructor to create an array. It will just create an array without any value with a given size. But the values of the array will be undefined.
Method 2: We will use apply() and map() methods to create an array with the given size. It will create an array without any value with a given size. But the values of the array will be undefined.
Method 3: We will use apply() and map() methods to create an array with the given size. This will create an array without any value with a given size. We will put the values of the indexes so it will give you an array of length 5 and its values will be the index number 0, 1, 2, 3, 4.
Method 4: In ES6, we got something new called JavaScript Array.from() function, by which we can create an array of a given size.
Method 5: If you want to create an array with specific values and with a given size, then simply put the array elements using JavaScript Array.from() function. This can be useful when you are trying to hold certain values in your array.
Example: In this example, we will pass the elements as arguments, each character will be an array element
Method 6 : In this method, we will use JavaScript Array.from() function and the repeat() function to create an array with a given size by repeating that number of times.
Example: In this example, we will pass a single element as a parameter and repeat the length we want in our array.
Method 7: In this method, we will use two features of ES6, one JavaScript Array.from() function and the arrow function to create an array with a given size.
To more about Arrays in JavaScript please go through Arrays in JavaScript
Please Login to comment...
- javascript-array
- JavaScript-Questions
- Web Technologies
New Course Launch!
Improve your Coding Skills with Practice
Start your coding journey now.

How to Create an Array Containing 1…N
In this tutorial, you are going to learn about creating a JavaScript Array that contains 1 through to n.
Let's create a new array with a specified length . The constructor sets the length property of the Array to the given length, without setting the keys.
Next, when you want to use it, for example, un-optimized do the following:
Watch a video course JavaScript - The Complete Guide (Beginner + Advanced)

Let's discuss another way of solving this problem. You can do the following:
Number.call(undefined, n) is equal to Number(n) that returns n .
Array.apply(null, [undefined, undefined, undefined]) is equal to Array (undefined, undefined, undefined) , which initializes three-element array and assigns undefined to each element.
Now let's generalize that to n elements. The Array() works like this:
Now let’s call Array.apply(null, { length: n }) :
Now we have an n -element array where each element is set to undefined.
When you invoke .map(callback, thisArg) on it, it will set each element to the result of callback.call(thisArg, element, index, array) .
Both Array.apply(null, {length: n}) and Array(n) expressions result an n -element array of undefined elements. According to the map() documentation, the first expression will set each element to undefined, whereas in the second expression, each element was never set.
The callback is called only for indexes of the Array which have assigned values, thus Array(n) is not productive; Array(n).map(Number.call, Number) would result in an uninitialized array of length n.

The Array() Constructor
The Array() constructor creates Array objects. A JavaScript array is created with the given elements, except in the case where a single argument is passed to the Array constructor and is a number. Array length property returns an unsigned, 32-bit integer that specifies the number of elements in the Array.
Related Resources
- How to Generate a Random Number Between Two Numbers in JavaScript
- How to Check if an Element is Present in an Array in JavaScript?
- How to Merge Two Arrays in JavaScript and De-duplicate Items
- How to Check for Empty/Undefined/Null String in JavaScript
- How to Remove an Element from an Array in JavaScript
- How to Insert an Item into an Array at a Specific Index
- How to Declare and Initialize an Array in JavaScript
- How to Access the Correct “this” Inside a Callback
- How To Add New Elements To A JavaScript Array
- How to Append an Item to an Array in JavaScript
- How to Convert String to Number in JavaScript
- How to Loop through an Array in JavaScript
- How to Empty an Array in JavaScript
- JavaScript Function Expressions
- JavaScript Array methods
- JavaScript Arrays

Dec 5, 2018
4 Ways to Populate an Array in JavaScript
Occasionally in JavaScript it’s necessary to populate an array with some defaults — an object, string or numbers. What’s the best approach for the job?
Lately, I’ve been working with Oleksii Trekhleb on a new book based on his Github repo: JavaScript Algorithms and Data Structures . As I’ve worked on writing some chapters and editing the book I came across some gotchas in working with arrays in JavaScript. There are a few different options for creating an array and filling it with default values in JavaScript, and this blog post explains the pros and cons of each option.
Using the Array.fill method is an obvious choice — you supply the method with the value you want to populate your array with, and the method returns a modified version of the array.
For example, if we want to set up an array with ten slots and populate it with the string “hello” we’d write some code like this:
let filledArray = new Array(10).fill('hello');
This method works great for immutable values like numbers, strings, and booleans. What if we wanted to populate an array with objects though?
This also populates the array with objects, but they all refer to the same object. In the MDN web docs on the fill method it says:
When fill gets passed an object, it will copy the reference and fill the array with references to that object.
So if we change that object like this:
It will change every object in the array because they are all referencing the same object. If we want to populate an array with unique objects, we’d need to use a different approach:
In this approach, we are creating an array with ten empty slots, then filling those slots with the null value, then creating a new array with unique objects. Now when we change an object in the array, we are only changing a specific object, not a reference to an object.
Using the map method is rather expensive though because the map method returns a completely new array, instead of using the existing array. For large datasets, this could get rather expensive. There are some other alternatives to populating an array with objects.
Using a for loop
Rather than using the fill and map methods, we could create a new array like this:
Then loop over the array the old fashioned way like this:
This avoids using the map method.
Using Array.from
Another alternative is to use the Array.from method. From the MDN docs:
Array.from() lets you create Arrays from: array-like objects (objects with a length property and indexed elements) or iterable objects (objects where you can get its elements, such as Map and Set).
In this one-liner, the first argument of the from method is the object we want to create an array from. In this case, we are creating an empty object with a length property set to 10. The second argument is a function that fills the array with whatever the result of our function is — in our case it is our hello object.
Using spread syntax
Our final option is to use the array spread syntax:
The array spread syntax allows you to expand an array or string and create a new array from the expanded elements. By using the array spread syntax, we avoid the need to use the fill method but we’re still using the map method which can get expensive.
I’m excited about the launch of this book in early March. Sign up below if you want to get more updates on book progress and get some good discounts when it launches!
Thanks to Devin Abbott and Nate Murray for help with writing this blog post.
More from Sophia Shoemaker
Editor of http://newsletter.fullstackreact.com, fan of all things React
About Help Terms Privacy
Get the Medium app

Sophia Shoemaker
Editor of http://newsletter.fullstackreact.com , fan of all things React
Text to speech
JS Tutorial
Js versions, js functions, js html dom, js browser bom, js web apis, js vs jquery, js graphics, js examples, js references, javascript arrays.
An array is a special variable, which can hold more than one value:
Why Use Arrays?
If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:
However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300?
The solution is an array!
An array can hold many values under a single name, and you can access the values by referring to an index number.
Creating an Array
Using an array literal is the easiest way to create a JavaScript Array.
It is a common practice to declare arrays with the const keyword.
Learn more about const with arrays in the chapter: JS Array Const .
Spaces and line breaks are not important. A declaration can span multiple lines:
You can also create an array, and then provide the elements:
Using the JavaScript Keyword new
The following example also creates an Array, and assigns values to it:
The two examples above do exactly the same.
There is no need to use new Array() .
For simplicity, readability and execution speed, use the array literal method.
Advertisement
Accessing Array Elements
You access an array element by referring to the index number :
Note: Array indexes start with 0.
[0] is the first element. [1] is the second element.
Changing an Array Element
This statement changes the value of the first element in cars :
Access the Full Array
With JavaScript, the full array can be accessed by referring to the array name:
Arrays are Objects
Arrays are a special type of objects. The typeof operator in JavaScript returns "object" for arrays.
But, JavaScript arrays are best described as arrays.
Arrays use numbers to access its "elements". In this example, person[0] returns John:
Objects use names to access its "members". In this example, person.firstName returns John:
Array Elements Can Be Objects
JavaScript variables can be objects. Arrays are special kinds of objects.
Because of this, you can have variables of different types in the same Array.
You can have objects in an Array. You can have functions in an Array. You can have arrays in an Array:
Array Properties and Methods
The real strength of JavaScript arrays are the built-in array properties and methods:
Array methods are covered in the next chapters.
The length Property
The length property of an array returns the length of an array (the number of array elements).
The length property is always one more than the highest array index.
Accessing the First Array Element
Accessing the last array element, looping array elements.
One way to loop through an array, is using a for loop:
You can also use the Array.forEach() function:
Adding Array Elements
The easiest way to add a new element to an array is using the push() method:
New element can also be added to an array using the length property:
Adding elements with high indexes can create undefined "holes" in an array:
Associative Arrays
Many programming languages support arrays with named indexes.
Arrays with named indexes are called associative arrays (or hashes).
JavaScript does not support arrays with named indexes.
In JavaScript, arrays always use numbered indexes .
WARNING !! If you use named indexes, JavaScript will redefine the array to an object.
After that, some array methods and properties will produce incorrect results .
Example:
The difference between arrays and objects.
In JavaScript, arrays use numbered indexes .
In JavaScript, objects use named indexes .
Arrays are a special kind of objects, with numbered indexes.
When to Use Arrays. When to use Objects.
- JavaScript does not support associative arrays.
- You should use objects when you want the element names to be strings (text) .
- You should use arrays when you want the element names to be numbers .
JavaScript new Array()
JavaScript has a built-in array constructor new Array() .
But you can safely use [] instead.
These two different statements both create a new empty array named points:
These two different statements both create a new array containing 6 numbers:
The new keyword can produce some unexpected results:
A Common Error
is not the same as:
How to Recognize an Array
A common question is: How do I know if a variable is an array?
The problem is that the JavaScript operator typeof returns " object ":
The typeof operator returns object because a JavaScript array is an object.
Solution 1:
To solve this problem ECMAScript 5 (JavaScript 2009) defined a new method Array.isArray() :
Solution 2:
The instanceof operator returns true if an object is created by a given constructor:
Complete Array Reference
For a complete Array reference, go to our:
Complete JavaScript Array Reference .
The reference contains descriptions and examples of all Array properties and methods.
Test Yourself With Exercises
Get the value " Volvo " from the cars array.
Start the Exercise

COLOR PICKER

Get your certification today!

Get certified by completing a course today!

Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
[email protected]
Your Suggestion:
Thank you for helping us.
Your message has been sent to W3Schools.
Top Tutorials
Top references, top examples, web certificates, get certified.
JavaScript Arrays - How to Create an Array in JavaScript
An array is a type of data structure where you can store an ordered list of elements.
In this article, I will show you 3 ways you can create an array using JavaScript. I will also show you how to create an array from a string using the split() method.
How to create an array in JavaScript using the assignment operator
The most common way to create an array in JavaScript would be to assign that array to a variable like this:
If we console.log the array, then it will show us all 4 elements listed in the array.

How to create an array in JavaScript using the new operator and Array constructor
Another way to create an array is to use the new keyword with the Array constructor.
Here is the basic syntax:
If a number parameter is passed into the parenthesis, that will set the length for the new array.
In this example, we are creating an array with a length of 3 empty slots.

If we use the length property on the new array, then it will return the number 3.
But if we try to access any elements of the array, it will come back undefined because all of those slots are currently empty.

We can modify our example to take in multiple parameters and create an array of food items.

How to create an array in JavaScript using Array.of()
Another way to create an array is to use the Array.of() method. This method takes in any number of arguments and creates a new array instance.
We can modify our earlier food example to use the Array.of() method like this.

This method is really similar to using the Array constructor. The key difference is that if you pass in a single number using Array.of() it will return an array with that number in it. But the Array constructor creates x number of empty slots for that number.
In this example it would return an array with the number 4 in it.

But if I changed this example to use the Array constructor, then it would return an array of 4 empty slots.

How to create an array from a string using the split() method
Here is the syntax for the JavaScript split() method.
The optional separator is a type of pattern that tells the computer where each split should happen.
The optional limit parameter is a positive number that tells the computer how many substrings should be in the returned array value.
In this example, I have the string "I love freeCodeCamp" . If I were to use the split() method without the separator, then the return value would be an array of the entire string.

If I wanted to change it so the string is split up into individual characters, then I would need to add a separator. The separator would be an empty string.

Notice how the spaces are considered characters in the return value.
If I wanted to change it so the string is split up into individual words, then the separator would be an empty string with a space.

In this article I showed you three ways to create an array using the assignment operator, Array constructor, and Array.of() method.
If a number parameter is passed into the parenthesis, that will set the length for the new array with that number of empty slots.
For example, this code will create an array with a length of 3 empty slots.
We can also pass in multiple parameters like this:
You can also take a string and create an array using the split() method
I hope you enjoyed this article on JavaScript arrays.
I am a musician and a programmer.
If you read this far, tweet to the author to show them you care. Tweet a thanks
Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

IMAGES
VIDEO
COMMENTS
One common way of creating an Array with a given length, is to use the Array constructor: const LEN = 3; const arr = new Array(LEN); assert
Actually, the array doesn't get filled with anything with new Array(n), not even 'undefined's, it simply sets the arrays length value to n. You can check this
Try the demo. Array(length).fill({ value: 0 }) creates an array of length 3 , and assigns to each item the { value: 0 } (note: same object
The fill() method changes all elements in an array to a static value, from a start index (default 0) to an end index (default array.length).
The length data property of an Array instance represents the number of elements in that array. The value is an unsigned, 32-bit integer that
Method 5: If you want to create an array with specific values and with a given size, then simply put the array elements using JavaScript Array.
In this tutorial, you are going to learn about creating a JavaScript Array that contains 1 through to n. ... Let's create a new array with a specified length. The
In this one-liner, the first argument of the from method is the object we want to create an array from. In this case, we are creating an empty
Using an array literal is the easiest way to create a JavaScript Array. Syntax: const array_name = [item1, item2, ...]; It is a common practice to declare
Another way to create an array is to use the new keyword with the Array constructor. Here is the basic syntax: new Array();. If a number