Use the array constructor to create an empty array JavaScript with size but you cannot iterate over. Below gives you an array with length 5 but no values, hence you can’t iterate over it.
Array(5)
new Array(5)
The above code, size
represents the desired length of the array. However, please note that the array created using new Array(size)
will contain empty or uninitialized items, and the length property will be set accordingly.
If you want to initialize the array with a specific value (e.g., empty string, zero, or null
), you can use the fill()
method to populate the array:
const size = 5;
const emptyArray = new Array(size).fill("");
console.log(emptyArray); // [ '', '', '', '', '' ]
In the code snippet above, the fill("")
method is used to populate each item in the array with an empty string. You can replace ""
with any other value you want to initialize the array with.
Create empty array JavaScript with size
A simple example code creates an array with size and access first element.
<!DOCTYPE html>
<html>
<body>
<script>
var arr = new Array(5);
console.log(arr.length)
console.log(arr[0])
</script>
</body>
</html>
Output:
You can create a new array, which can be iterated over like below:
a) All JavaScript versions
- Array.apply:
Array.apply(null, Array(100))
b) From the ES6 JavaScript version
- Destructuring operator:
[...Array(100)]
- Array.prototype.fill
Array(100).fill(undefined)
- Array.from
Array.from({ length: 100 })
You can map over these arrays like below.
Array(4).fill(null).map((u, i) => i)
[0, 1, 2, 3][...Array(4)].map((u, i) => i)
[0, 1, 2, 3]Array.apply(null, Array(4)).map((u, i) => i)
[0, 1, 2, 3]Array.from({ length: 4 }).map((u, i) => i)
[0, 1, 2, 3]
Alternatively, if you are using newer versions of JavaScript (ES6+), you can use the Array.from()
method to create an array with a specified length and a default value:
const size = 5;
const defaultValue = null;
const emptyArray = Array.from({ length: size }, () => defaultValue);
console.log(emptyArray); // [ null, null, null, null, null ]
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