Creating an array of a given size can be implemented in many ways, and each way is useful in some conditions. We will explain each possible ways to create an array with the given size with a proper example.
![]() |
Create an array of given size in JavaScript |
Method 1: In this method, we use the JavaScript Array constructor to create an array. It will just create an array without any value with a given size. But the values of the array will be undefined.
<script> var arr = new Array(5); console.log(arr.length); console.log(arr) </script>
Output:
5 [undefined, undefined, undefined, undefined, undefined]
Method 2: We will use apply() and map() methods to create an array with the given size. It will create an array without any value with a given size. But the values of the array will be undefined.
<script>
var arr = Array.apply(null, Array(5))
.map(function () {});
console.log(arr.length);
console.log(arr);
</script>
Related Posts
5 [undefined, undefined, undefined, undefined, undefined]