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!

Foxi - Budget Planner & Tracker

Foxi

Budget Planner & Tracker

More money in your pocket by the end of the month.

Free to use and no account needed.

Get started now.

Get the app

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

Become an expert in ReactJS, TypeScript, and JavaScript.

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.

Good things are coming, don't miss out!

Good things are coming, don't miss out!

Follow me on Twitter to stay up to date and learn frontend, React, JavaScript, and TypeScript tips and tricks!

Are you a novice, intermediate or expert react engineer?

Find out here by taking my fun, interactive, quick quiz which takes approximately 1 - 3 minutes. How well will you will do?

Foxi - Budget Planner & Tracker

Foxi

Budget Planner & Tracker

More money in your pocket by the end of the month.

Free to use and no account needed.

Get started now.

Get the app