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:

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:

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 ranges of integer values   #

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 :

Filled with arbitrary values:

Ranges of integers:

Recommended patterns   #

I prefer the following approaches. My focus is on readability, not on performance.

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   #

Further reading   #

Headshot of Dr. Axel Rauschmayer

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?

dil's user avatar

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 .

Brian Burns's user avatar

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:

zertosh's user avatar

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

Conclusions

enter image description here

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:

enter image description here

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:

Lucio Paiva's user avatar

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.

Gerald Senarclens de Grancy's user avatar

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>

T.J. Crowder's user avatar

If you use ES6, you can use Array.from() like this:

Has the same result as

foxiris's user avatar

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.

Community's user avatar

Note that while is usually more efficient than for-in , forEach , etc.

kangax's user avatar

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.

Allen Rice's user avatar

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.

Matthew Crumley's user avatar

ES6 solution:

Vic's user avatar

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

аlex dykyі's user avatar

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.

Nenad Vukicevic's user avatar

Using lodash or underscore

Or if you have an array existing and you want an array of the same length

djechlin's user avatar

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]

Salvador Dali's user avatar

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)]);

Juanma Menendez's user avatar

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

Firefox 20.0

Missing the most important test (at least for me): the Node.js one. I suspect it close to Chrome benchmark.

durum's user avatar

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.

Isaac B's user avatar

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.

Eugene Tiurin's user avatar

What about new Array(51).join('0').split('') ?

Cory Mawhorter's user avatar

let filled = []; filled.length = 10; filled.fill(0); console.log(filled);

Tomiwa Adefokun's user avatar

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):

Sam Barnum's user avatar

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) .

Frederik Gottlieb's user avatar

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.

Ivo's user avatar

Shortest for loop code

Safe var version

nathnolt's user avatar

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 ? :-)

Joshua's user avatar

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).

annakata's user avatar

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

Mateo Gianolio's user avatar

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

Hot Network Questions

javascript create array of length with values

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 .

Home

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:

Subscribe to my newsletter to get them right into your inbox.

Dmitri Pavlutin

About Dmitri Pavlutin

Recommended reading:, 5 handy applications of javascript array.from(), 15 common operations on arrays in javascript (cheatsheet), popular posts.

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:

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.

Related Articles

Create an array of given size in JavaScript

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...

New Course Launch!

Improve your Coding Skills with Practice

Start your coding journey now.

w3docs logo

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)

w3docs logo

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

Sophia Shoemaker

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

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store

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 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

Get started with your own server with Dynamic Spaces

COLOR PICKER

colorpicker

Get your certification today!

javascript create array of length with values

Get certified by completing a course today!

Subscribe

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.

Screen-Shot-2022-05-01-at-11.11.38-PM

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.

Screen-Shot-2022-05-14-at-11.07.33-PM

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.

Screen-Shot-2022-05-14-at-11.10.02-PM

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

Screen-Shot-2022-05-14-at-11.13.48-PM

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.

Screen-Shot-2022-05-14-at-11.47.54-PM

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.

Screen-Shot-2022-05-15-at-12.00.27-AM

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

Screen-Shot-2022-05-15-at-12.02.03-AM

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.

Screen-Shot-2022-05-15-at-12.09.10-AM

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.

Screen-Shot-2022-05-15-at-12.10.58-AM

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.

Screen-Shot-2022-05-15-at-12.11.32-AM

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

  1. 34 Javascript Array Length Vs Size

    javascript create array of length with values

  2. 35 Javascript New Array Length

    javascript create array of length with values

  3. Math Floor Random Array Length

    javascript create array of length with values

  4. JavaScript

    javascript create array of length with values

  5. Create Empty Vector In R

    javascript create array of length with values

  6. Javascript array find: How to Find Element in Javascript

    javascript create array of length with values

VIDEO

  1. Multidimensional Array .length JavaScript #javascript #java #array #length #loop #shorts #viral

  2. Javascript

  3. 10_ARRAY IN Python -1

  4. How to create Array on Numpy

  5. 9 JavaScript Array

  6. Javascript, set an array values to unique #javascript #shorts

COMMENTS

  1. Creating and filling Arrays of arbitrary lengths in JavaScript

    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

  2. Most efficient way to create a zero filled JavaScript array?

    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

  3. How to Fill an Array with Initial Values in JavaScript

    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

  4. Array.prototype.fill()

    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).

  5. 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

  6. Create an array of given size in JavaScript

    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.

  7. 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

  8. 4 Ways to Populate an Array in JavaScript

    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

  9. JavaScript Arrays

    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

  10. JavaScript Arrays

    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