Difference Between “Array()” and “[]” JS Array Declaration
The “Array()” and “[]” are used to declare new array JavaScript. The Array() is the constructor method of array and the [] syntax is knowns as array literal. The [] array literal is a simple and mostly preferred way to declare an array while Array() constructor may lead to some unexpected behaviors in case of empty elements, single numeric elements etc.
// Declaration using Array constructor
let myArray = new Array(5);
// Declaration using Array Literal
let myArray = [5];
Array() Constructor
The array constructor method is used to initialize an array of values passes in the arguments. But in case of single numeric argument it creates an array of size 5 instead.
const a = new Array(5);
console.log(a);
console.log(a.length);
Output
Array: [ <5 empty items> ] Size of Array: 5
This method is used to define an array of length 5. The parameter passed here ‘5’ is an argument that defines the initial length of the array to be made. Hence any value can be passed to get the array of that length using this code.
Another advantage of using this method is that it creates the required size of the array beforehand in the stack. This, in turn, helps to avoid StackOverflow error.
Using [] Array Literals
This method is used to define an array of with the values where the length of the array is equal to the number of values passed to in the square brackets. The parameter passed here ‘5’ is the value for myArray’s 0th element, i.e. myArray[0] = 5.
// Creates an array of 5 undefined elements
let arr = [5];
console.log(arr);
console.log(arr.length);
Output
Array: [ 5 ] Size of Array: 1
This method does not create the required size of the array beforehand in the stack. Hence this method needs the memory to be defined every time the array expands, which in turn can lead to StackOverflow error.
Difference Between Array() and [] Array Declaration
Feature | Array Literal [] | Array Constructor Array() |
---|---|---|
Syntax | Simple and concise | Verbose |
Output for Single Numeric Argument | [5] → [5] | Array(5) → [ <5 empty items> ] |
Output for Multiple Arguments | [1, 2, 3] → [1, 2, 3] | Array(1, 2, 3) → [1, 2, 3] |
Best Practice | Preferred | Avoid unless needing empty slots |