Blog / Javascript

How to initialize an array with values in JavaScript

How to initialize an array with values in JavaScript

In this short post we will look at how to initialize an array with values in JavaScript in a simple and easy way that will work for n values of any size.

Will MaygerWill Mayger
November 23, 2021
Article

In JavaScript arrays are fairly straight forward in the sense we don’t have to worry about allocating their size most of the time because that will all be handled for us.

However there are occasions where it does come in handy to be able to initialize an array with n values in JavaScript where n is the size we want.

In this post we will go over how to initialize an empty array in JavaScript and then fill it as well.

How to initialize an array with values in JavaScript

To initialize and fill an array with n values in JavaScript, one of the easiest ways is to make use of the Array.prototype.fill method which let’s us fill an empty array with a given value.

All we have to do is firstly, create an empty array with a size of n, and then call Array.prototype.fill on it to give the empty array values of our choice.

Here is an example of how to initialize array with values in JavaScript:

const n = 2;
const value = "example";
const newArray = Array(n).fill(value);
console.log(newArray); // ["example", "example"]
initialize array with values javascript

Summary

There we have how to initialize an array with values in JavaScript, if you want more like this be sure to check out some of my other posts!

I hope this post has helped, but before you go I highly recommend that you checkout Pluralsight if you are interested in improving your software engineering skills, such as React, JavaScript, or Typescript (and much more).

Not only does Pluralsight provide you with all the learning material you need but it also let's you learn in a fun, interactive way and gives you the ability to see your current progress and level in a certain skill via their Skill Assessment tool which can help you see what you need to learn next to keep improving!

Learn React, JavaScript and TypeScript

Learn React, JavaScript and TypeScript

Join the platform that top tier companies are using.
Master the skills you need to succeed as a software engineer and take your career to the next level with Pluralsight.

Start here

Some graphics used on this post were made using icons from flaticon.

Latest Posts

Learn React, JavaScript and TypeScript

Learn React, JavaScript and TypeScript

Join the platform that top tier companies are using.
Master the skills you need to succeed as a software engineer and take your career to the next level with Pluralsight.

Start here

Earn more and take your coding career to the next level.

Here you will find my personal recomendations to you, for full disclosure I earn a small commission from some of these links, but I only recommend what I trust and personally use.