0
0
JavascriptHow-ToBeginner · 3 min read

How to Create an Array of n Elements in JavaScript

To create an array with n elements in JavaScript, use Array(n) to make an empty array of length n. To fill it with values, use Array(n).fill(value) or Array.from({ length: n }, () => value).
📐

Syntax

Here are common ways to create an array of n elements:

  • Array(n): Creates an empty array with length n.
  • Array(n).fill(value): Creates an array of length n filled with value.
  • Array.from({ length: n }, () => value): Creates an array of length n with each element set by the function.
javascript
const n = 5;
const emptyArray = Array(n);
const filledArray = Array(n).fill(0);
const fromArray = Array.from({ length: n }, () => 1);
💻

Example

This example shows how to create arrays of 5 elements: empty, filled with zeros, and filled with ones.

javascript
const n = 5;

const emptyArray = Array(n);
console.log('Empty array:', emptyArray);

const filledArray = Array(n).fill(0);
console.log('Filled with zeros:', filledArray);

const fromArray = Array.from({ length: n }, () => 1);
console.log('Filled with ones:', fromArray);
Output
Empty array: [ <5 empty items> ] Filled with zeros: [ 0, 0, 0, 0, 0 ] Filled with ones: [ 1, 1, 1, 1, 1 ]
⚠️

Common Pitfalls

A common mistake is to create an array with Array(n) and expect it to have usable elements. This creates an array with empty slots, not undefined values, so methods like map won't work as expected.

To fix this, use fill or Array.from to initialize elements.

javascript
const n = 3;

const wrong = Array(n).map(() => 0);
console.log('Wrong:', wrong); // Outputs: [ <3 empty items> ]

const right = Array(n).fill(0).map(() => 0);
console.log('Right:', right); // Outputs: [ 0, 0, 0 ]
Output
Wrong: [ <3 empty items> ] Right: [ 0, 0, 0 ]
📊

Quick Reference

MethodDescriptionExample
Array(n)Creates empty array of length nArray(4)
Array(n).fill(value)Creates array filled with valueArray(4).fill(0)
Array.from({ length: n }, () => value)Creates array with values from functionArray.from({ length: 4 }, () => 1)

Key Takeaways

Use Array(n) to create an empty array of length n.
Use fill() or Array.from() to initialize array elements.
Empty slots in Array(n) do not behave like undefined values.
Methods like map() need arrays with initialized elements to work properly.