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

default array values

Is there a way to assign a default values to arrays in javascript?

ex: an array with 24 slots that defaults to 0

Esko's user avatar

18 Answers 18

You can use the fill function on an array:

Note: fill was only introduced in ECMAScript 2015 (alias "6"), so as of 2017 browser support is still very limited (for example no Internet Explorer).

sleske's user avatar

var A= [].repeat(0, 24);

kennebec's user avatar

the best and easiest solution is :

and result will be

you can put any thing you like in it:

Now if you want to change some of the current value in the array you can use

and output is

Sajad Saderi's user avatar

A little wordy, but it works.

tvanfosson's user avatar

If you use a "very modern" browser (check the compatibility table ), you can rely on fill :

For several reasons, the use of new Array() is not appreciated by a lot of developers; so you can do the same as follows:

The latter is much more compatible, and as you can see both solutions are represented by two lines of code.

Vito Gentile's user avatar

I personally use:

Thomas Eding's user avatar

If you are using ES6 and up you can use

this also works:

Oscar Rieken's user avatar

You have to use a loop.

kennytm's user avatar

And now, more cleverly :) @see JavaScript Array reference Example on JSFiddle

Tomáš's user avatar

Use Lodash ( https://lodash.com/docs ), a robust library for array manipulation which is available for browser too.

Aman Gupta's user avatar

Another way to achieve the same -

Array.from(Array(24),()=>5)

Array.from accepts a second param as its map function.

Sunny R Gupta's user avatar

Simplest one:

Nishant's user avatar

Syntax which i am using below is based on ECMA Script 6/es6

let arr=[];

arr.length=5; //Size of your array;

[...arr].map( Boolean ).map( Number ); //three dot operator is called spread Operator introduce in ECMA Script 6

------------Another way-------------

let variable_name=new Array(size).fill(initial_value)

for ex- let arr=new Array(5).fill(0) //fill method is also introduced in es6

Another way as per ECMA 5 or es5

var variable_name=Array.apply(null,Array(size)).map(Boolean).map(Number)

var arr=Array.apply(null,Array(5)).map(Boolean).map(Number);

All of them will give you same result : [0,0,0,0,0]

Bhanu Negi's user avatar

serious's user avatar

If you want BigO(1) instead of BigO(n) please check below solution:

Default value of an array is undefined . So if you want to set default to 0, you have to loop all elements of array to set them to 0.

If you have to do that, it's ok. But I think it'll better if you check the value when want to get value of the element.

Define a function 'get': to get value of the array. myArray[index], if myArray[index] undefined, return '0', else return the value.

SLyHuy's user avatar

Your Answer

Sign up or log in, post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service , privacy policy and cookie policy

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

Hot Network Questions

javascript create array with default 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 .

Frontend Essentials

Frontend Essentials

Cristian Salcescu

Mar 22, 2021

Member-only

How to Fill an Array with Defaults

The array built-in function, the fill and map array methods, and more.

There are cases when we want to create an array filled with default values. For small arrays, of course, we can just write down the values when declaring the array but for larger arrays, a nicer system may be needed.

More from Frontend Essentials

Learn more on JavaScript, functional programming, and front-end development.

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

Cristian Salcescu

Author of Functional Programming in JavaScript. Enthusiastic about sharing ideas. https://www.amazon.com/gp/product/B08X3TPCQ8

Text to speech

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

Javascript Tutorial

Mapping an array to a new array with default values in JavaScript

Suppose, we have an array of start times and stop times for a stopwatch like this −

We are required to write a JavaScript function that takes one such array. Our function needs to turn them into one final array that is the actual amount of time that passed for each entry.

Therefore, for the above array, the output should look like −

The code for this will be −

And the output in the console will be −

AmitDiwan

Tutorials Point

Swift Developer Blog

Learn Swift and App Development for iOS

Create An Array with Default Values

[raw_html_snippet id=”cookbookpagecoursesheader”]

Unit Testing Swift Mobile App

javascript create array with default values

Would you like more video tutorials weekly?

Enter your email and stay on top of things,

Technical Potpourri from Sudipta Deb

Select Page

Fill an Array with Initial Values in JavaScript

Posted by Sudipta Deb | May 9, 2022 | javascript , JavaScript Certification , Uncategorized , Web Technology | 1

Fill an Array with Initial Values in JavaScript

Arrays can be initialised with data in a variety of ways in JavaScript. Let’s examine which methods are the easiest and most popular in this post.

Read this blog post or watch the  video below to learn more about different ways to fill an array with initial values in JavaScript .

Down Arrow

#1 Fill an array with primitives

Let’s say, you want to initialize an array of elements 5 with the number 1. You can use the array.fill(initialValue) method to initialize an array. This method will return the modified array.

The thing that you need to keep in mind is the usage of array.fill(initialValue) in combination with Array(n) constructor.

Array(length) creates the sparse array. If you are not aware of sparse array, please read my previous blog: Sparse vs Dense Arrays in JavaScript . So Array(length).fill(1) basically modifies the array by putting 1 in every index of the array and finally returning the array like [1, 1, 1, 1, 1].

Array(length).fill(initialValue) is a convenient way to create arrays with the desired length and initialized them with a primitive value (number, string, boolean).

#2 Fill an array with objects

What if you need to add objects to an array? Whether you want the array filled with the initial object instances or with other instances, this need is significantly complicated.

#2.1 array. fill (initialValue)

If you want to initialize the array with the same object instance, then you can use array.fill() method.

Array(length).fill({stage:1}) creates an array with length 4 and at the same time put the same object i.e. {stage : 1} on each index of the array.

The important thing that you need to remember is that each of the index is filled with same object instance. So if you want to change one index of the array, it will not only change that index, rather it will change every index of the array. Refer to the program below 

#2.2 array. from ()

If you want to fill the array by creating copies from another array, then you can use array.from() method.

Array.from( array, mapperFunction )  accepts two arguments: an array (from which elements will be copied) and a mapperFunction (a function which will be called for each element of the original array).

Array.from() will invoke the mapperFunction on each item of the array and then pushes the result to a new array, and finally the newly mapped array.

With this approach, if you change some element of the array, only that element is changed, not the entire array. 

#2.3 array. map ()  with spread operator

When you use Array.length() to create an array, it creates a sparse array and using map() function on the sparse array skips the empty indexes from the array.

But using the spread operator you can transform a sparse array into an array with items initialized with undefined . After that, you can apply array.map() method on that array.

The expression […Array(length)] creates the array where items are initialized with undefined . And then applying map() to create new instances.

There are several good approaches to fill an array with initial values in JavaScript.

If you want to create an array using primitive values, the best method is to use Array (length). fill(initialValue) .

If you want to create an array with object instances but don’t care if each item has the same object instance, use Array (length) . The method to use is fill(initialObject) .

Otherwise, you might use Array.from(Array.length, mapper) or […Array(length)] to populate an array with distinct object instances. map(mapper), where mapper is a function that, on each invocation, returns a new object instance.

נערות ליווי בתל אביב- israel night club

Hello there! I simply would like to give you a huge thumbs up for your excellent information youve got here on this post. I will be returning to your site for more soon.

Submit a Comment Cancel reply

Your email address will not be published. Required fields are marked *

Save my name, email, and website in this browser for the next time I comment.

Submit Comment

About The Author

Sudipta Deb

Sudipta Deb

Enterprise Cloud Architect, Content Creator, 20x Salesforce Certified, 1x Google Cloud Certified, 2x Copado Certified

Related Posts

Understand Combinator, Attribute, Pseudo-class & Pseudo-elements Selectors – Part 3 of Fundamental CSS Tutorial

Understand Combinator, Attribute, Pseudo-class & Pseudo-elements Selectors – Part 3 of Fundamental CSS Tutorial

August 25, 2021

Understanding JavaScript Promises

Understanding JavaScript Promises

February 10, 2019

Practical Usage of Closure in JavaScript

Practical Usage of Closure in JavaScript

April 27, 2021

Understand JavaScript Closure

April 20, 2021

Recent Posts

javascript create array with default values

Apex Architect array Async attribute B2B B2C Best Practices combinator css css3 dense array Developer development Enhanced Domain Flow Google Cloud Google Cloud Certification Google Cloud Digital Leader Google Cloud Platform group husky ide JavaScript Kubernetes let Loyalty Management Promises pseudo-class pseudo-elements Release Salesforce Salesforce Certification scope Security selectors SOQL sparse array specificity specificity-rules Spring 23 TypeScript Virtual Machine vscode web

Recent Comments

How to Create an Array with Default Value in Swift?

Swift – create an array with default value.

To create an array with default value in Swift, use Array initialiser syntax and pass this default value. We also need to pass the size of the Array for the Array initialiser.

The syntax of Array initialiser to create an array with specific default value, is

The following code snippet returns an Array of size 4 with default value of 0 . The datatype of this array is inferred from the repeating value, which is the default value.

In this example, we will create a String Array with default value of "abc" . So repeating in the Array initialiser would be "abc" . To use Array initialiser syntax, we need to pass count as well. Let us give a value of 8 for the count .

In this Swift Tutorial , we learned how to create an Array with specific default value using Array initialiser syntax.

What do you need our team of experts to assist you with?

We'll be in touch soon!

IMAGES

  1. How To Create Nested Array In Java

    javascript create array with default values

  2. 39 Define 2d Array In Javascript

    javascript create array with default values

  3. javascript take a flat array and create a new array with grouped arrays by object property Code

    javascript create array with default values

  4. How To Write An Array

    javascript create array with default values

  5. Basics of javascript Array 1

    javascript create array with default values

  6. Math Floor Random Array Length

    javascript create array with default values

VIDEO

  1. Creating arrays [29 of 51]

  2. Creating Array and Fetching Elements in JavaScript

  3. #32 Array of Objects in Java

  4. #28 Creation of Array in Java

  5. How to create a 2D array in JavaScript

  6. sort Array Method

COMMENTS

  1. default array values

    Default value of an array is undefined . So if you want to set default to 0, you have to loop all elements of array to set them to 0. If you

  2. How to Fill an Array with Defaults

    There are cases when we want to create an array filled with default values. For small arrays, of course, we can just write down the values

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

    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

  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() constructor

    Syntax. new Array ; Array literal notation · const · = ; Array constructor with a single parameter · const · = ; Array constructor with multiple parameters · const · =

  6. Mapping an array to a new array with default values in JavaScript

    Mapping an array to a new array with default values in JavaScript ... const arr = [ { startTime: 1234, stopTime: 2345 }, { startTime: 3452

  7. Create An Array with Default Values

    Create An Array with Default Values · // Create an Array of Strings · var appleProgrammingLanguages: · // Thanks to Swift's type inference, you don't have to write

  8. Fill an Array with Initial Values in JavaScript

    If you want to initialize the array with the same object instance, then you can use array.fill() method. ... Array(length).fill({stage:1}) creates

  9. How to Create an Array with Default Value in Swift?

    To create an array with default value in Swift, use Array initialiser syntax and pass this default value. We also need to pass the size of the Array for the

  10. Changing Array Default Values

    Complete the following steps to manipulate the default values of an array. Create a 1D array shell in the front panel window. Add