Skip to content

JavaScript create array with N elements | Example code

  • by

Use the Array constructor and fill() method to create an array with N elements in JavaScript. Call the Array() constructor with a number will create an empty elements array.

var foo = new Array(100).fill('DefaultValue');

JavaScript creates an array with N elements

A simple example code creates an array containing 3 elements. All values in the Array will be the same.

<!DOCTYPE html>
<html>
<body>

<script>

   const arr = Array(3).fill('A');

   console.log(arr);

</script>

</body>
</html> 

Output:

JavaScript create array with N elements

A very similar approach is to use the Array.from method to get an array containing N undefined values.

const arr = Array.from({length: 3}).fill('a');

console.log(arr);

Fill the array with a range

function range(start, end) {
  return Array(end - start + 1).fill().map((_, idx) => start + idx)
}
var result = range(9, 18); // [9, 10, 11, 12, 13, 14, 15, 16, 17, 18]
console.log(result);

Do comment if you have any doubts or suggestions on this JS Array topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

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