How to Create an Array of Size N in JavaScript?

To quickly create an array of size n in JavaScript, you can use the Array() constructor. When you pass a single parameter to the Array() constructor, it creates an empty array of that size.

Now, to fill these empty slots with a default value such as 0, you can use the Array.fill() method. The fill() method fills each array slot with the same specified value.

See the following example:

const arr = new Array(10);
// Create an empty array of size 10

arr.fill(0);
// Fill each slot with value 0

console.log(arr);
// 👉 Output: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

Create Array of Size N using Array.from() Method

Another simpler approach to create an array of size n is to use the Array.from() method. The Array.from() method can take the length of the array as a parameter and create an empty array of that length filled with undefined values.

To fill those empty slots you can use the same Array.fill() method as we did in the previous example.

See the following example:

const arr = Array.from({length: 10});
// Create an empty array of size 10(filled with undefined values)

arr.fill(0);
// Fill each slot with value 0

console.log(arr);
// 👉 Output: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.