How to Check if Array is Empty in Javascript

In this tutorial, you will learn how to check if an array is empty in javascript. In an array, you can dynamically add or remove items.  Sometimes it becomes impossible to keep track of the presence of those items in an array.  As a result, you might end up trying to access an item by its index in an empty array.

It is extremely important to verify if the array is empty or not before even accessing any of its items.  This will help you in reducing the number of unforeseen bugs in production.

To solve the above problem, we will make use of the length property.  Arrays have built-in length property which returns the total number of items in an array.  If the length is 0, that means the array is empty.

In the following example, we have an empty array and we will use the length property to verify if the array is empty or not.  Please have a look over the code example and steps given below.

HTML & CSS

  • We have 3 elements in the HTML file (div, button, and h1). The div element is just a wrapper for the rest of the elements.
  • The inner text for the button element is “Check” and for the h1 element is “Result”.
  • We have done some basic styling using CSS and added the link to our style.css stylesheet inside the head element.
  • We have also included our javascript file script.js with a script tag at the bottom.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="style.css">
    <title>Document</title>
</head>
<body>
    
    <div>
        <button>Check</button>
        <h1>Result</h1>
    </div>

    <script src="script.js"></script>
</body>
</html>
body {
    text-align: center;
}

div {
    display: inline-block;
}

button {
    display: inline-block;
    padding: 10px 20px;
}

Javascript

  • We have selected 2 elements button and h1 using the document.querySelector() method and stored them in btnCheck and result variables respectively.
  • We have a global variable user and it holds an empty array as its value.
  • We have attached the click event listener to the button element.
  • In the event handler function, we are making use of the length property to get the length of the array.
  • If length is equal to 0, that means the array is empty.  Depending upon the result of verification, we are displaying the Boolean value in the h1 element. In our case, the array is empty so we will get True as a result.
let btnCheck = document.querySelector('button');
let result = document.querySelector('h1');

let users = [];

btnCheck.addEventListener('click', () => {
    result.innerText = users.length == 0 ? 'True' : 'False';
});