This quick tutorial will show you how to check whether an array is empty in the JavaScript programming language.
What is an Array?
An array is a type of variable that holds a collection of zero or more values. In JavaScript, arrays are ordered – each value in the array has a position (called the index) in the array, which is used to access it. Indexes start counting at 0, so the first value in an array is at index 0.
Declaring an Array in JavaScript
The quickest way to declare an array in JavaScript is to use the square bracket ([]) syntax:
var myEmptyArray = []; // Declare an empty array var myArray = [1, 2, 3]; / Declare an array containing the numerical values 1, 2 and 3
Adding Items to an Array
The quickest way to append a value to an array is using the push() method:
var myArray = [1, 2, 3]; myArray.push(4); // Appends the numerical value 4 to the array
Emptying/Resetting an Array
As covered in our article on resetting arrays in JavaScript, the quickest way to empty an array is to set its length property to 0:
var myArray = [1, 2, 3]; // Declare a populated array myArray.length = 0; // Resets the array
Checking if an Array is Empty
An empty array will have nothing in it – meaning it will have a length of 0.
So, to check if an array is empty, simply check whether it has a zero-length:
var myEmptyArray = []; // Declare an empty array if(myEmptyArray.length === 0 ){ // Array is empty }
Conversely, if an array’s length is greater than 0, it must be populated:
var myArray = [1, 2, 3]; // Declare a populated array if(myArray.length > 0 ){ // Array is not empty }
Remember! Array indexes start counting at 0 – so you cannot use indexes to check if an array is populated. Instead, you must check the array length.