How to Declare Empty Array in JavaScript

Kirill Ibrahim Feb 02, 2024
  1. JavaScript Declare Empty Array Example
  2. Difference Between Two Ways to Declare Empty Array in JavaScript
How to Declare Empty Array in JavaScript

JavaScript has different ways to declare an empty array. One way is to declare the array with the square brackets, like below.

var array1 = [];

The other way is to use the constructor method by leaving the parameter empty.

var array1 = new Array();

JavaScript Declare Empty Array Example

// Wider scope variable array:
var array1 = [];

// Local scope variable array:
let array2 = [];

let array3 = new Array();

console.log({array1, array2, array3});

Output:

{array1: Array(0), array2: Array(0), array3: Array(0)}

Difference Between Two Ways to Declare Empty Array in JavaScript

If we use the constructor method new Array(), we can pass a number in the constructor representing the length of an array.

Example:

let array1 = new Array(4);
console.log(array1.length);
let array2 = [];
console.log(array2.length);

Output:

4
0

At this point, new Array(4) will not actually add four undefined items to the array. It just adds space for four items.

Example:

let array1 = new Array(4);
console.log(array1[0]);
console.log(array1[1]);
console.log(array1[2]);
console.log(array1[3]);

Output:

undefined
undefined
undefined
undefined

Be aware that you can not rely on array.length for calculations when you want to check about the empty array.

Example:

let array1 = new Array(4);
let array2 = [];
array1.push('orange');
array2.push('orange');
console.log({array1, array2});

Output:

{ array1: [ <4 empty items>, 'orange' ], array2: [ 'orange' ] }

Related Article - JavaScript Array