Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Create empty array of a given size in JavaScript
In JavaScript, you can create an empty array of a given size using several approaches. The most common method is using the Array() constructor.
Using Array Constructor
The new Array(size) creates an array with the specified length, but all elements are undefined (empty slots).
var numberArray = new Array(5);
console.log("Array length:", numberArray.length);
console.log("Array contents:", numberArray);
console.log("First element:", numberArray[0]);
Array length: 5 Array contents: [ <5 empty items> ] First element: undefined
Filling the Array with Values
After creating an empty array, you can assign values to specific positions or replace the entire array.
var numberArray = new Array(6);
console.log("Initial length:", numberArray.length);
// Assigning new array values
numberArray = [10, 20, 30, 40, 50, 60];
console.log("Updated array:");
for(var i = 0; i < numberArray.length; i++) {
console.log("Index " + i + ":", numberArray[i]);
}
Initial length: 6 Updated array: Index 0: 10 Index 1: 20 Index 2: 30 Index 3: 40 Index 4: 50 Index 5: 60
Alternative Methods
You can also create arrays using other approaches:
// Using Array.from()
var arr1 = Array.from({length: 4});
console.log("Array.from():", arr1);
// Using fill() to initialize with a value
var arr2 = new Array(3).fill(0);
console.log("With fill(0):", arr2);
// Using spread operator
var arr3 = [...Array(3)];
console.log("Spread operator:", arr3);
Array.from(): [ undefined, undefined, undefined, undefined ] With fill(0): [ 0, 0, 0 ] Spread operator: [ undefined, undefined, undefined ]
Comparison of Methods
| Method | Creates | Initial Values |
|---|---|---|
new Array(size) |
Empty slots | undefined (sparse array) |
Array.from({length: size}) |
Dense array | undefined |
new Array(size).fill(value) |
Dense array | Specified value |
Conclusion
Use new Array(size) for basic empty arrays, or Array.from({length: size}) when you need to iterate immediately. The fill() method is ideal when initializing with default values.
Advertisements
