How to check if an array is empty in JavaScript
An array is a data structure that can store multiple values. In JavaScript, arrays are heterogenous i.e., arrays in JavaScript can store multiple values of the same or different types.
In JavaScript, arrays can be created using the square brackets [] notation or by using the array constructor new Array(). The square bracket notation is preferred.
For example, the following piece of code creates an array of strings:
const coursesArray = ["Cracking the Coding Interview", "System Design Demystified"]
Let's understand the length property to check the emptiness of the array.
The length property
The length property of an array returns the number of elements present in the array. For example, the following piece of code will return 2 because there are 2 elements in the coursesArray.
console.log(coursesArray.length); // 2
The length property of an array can be used to check if the array is empty or not. For example, if the length of an array is 0, the array is considered empty.
Code example
The following code example demonstrates how to use the length property to check the emptiness of an array.
const emptyArray = []; // An array with no elementsconst arrLength = emptyArray.length;if(arrLength === 0){console.log("Array is empty");}else{console.log("Array is not empty");}
Here's an explanation of the code above:
Line 1: We create an empty array named
emptyArray.Line 2: We use the
lengthproperty to find the length ofemptyArrayand store its value in a variable namedarrLength.Lines 4-9: We define a decision-making statement based on
arrLength. IfarrLengthis equal to0, then"Array is empty"will be printed. If it is not equal to0, then"Array is not empty"will be printed.