Loading...

Easy Ways to Check If an Array is Empty in JavaScript

Pravin Prajapati  ·   03 May 2024
Check if an array is empty in JavaScript
service-banner

Every developer must be aware of Java scripts, and working with arrays is the foundation of many web development tasks. These arrays could be generated by your website's server, from an external source such as an API, or by yourself. Checking if an array is empty is a common task in JavaScript, and several efficient ways exist.

Here is a simple way to truthfully check empty arrays in javascript. In this short guide, we'll cover four simple methods for checking if an array is empty.

  1. Applying the length property with the === operator
  2. Applying the length property with the ! operator
  3. Applying the Array.isArray() method
  4. Gotcha: Applying the === [] syntax

1. Applying the length property with the === operator

To Check Empty Array in JavaScript, use the length property with the === operator. The length property indicates how many items exist in the array. If it's empty, the length will be 0, so you can check if the length is exactly 0 to see if the array is empty.

For example, if you have an empty array called names:

const names = [];
const isEmpty = names.length === 0; // true

// And if you have an array with some items:

const names = ['Ram', 'Rohan'];
const isEmpty = names.length === 0; // false

But there are some things to be careful about when using this method, and we'll discuss them later in this article.

2. Applying the length property with the ! operator

The second method to check if a JavaScript array is empty is using the length property with the! Operator. The! operator is the logical NOT operator. Since 0 is considered false in JavaScript, we can use ! to flip the truthiness of the length property.

If your array is empty, the length property will be 0 (which is false), so the expression will return true:

const names = [];
const isEmpty = !names.length; // true

// If your array is not empty, the length property will be an integer greater than 0 (which is true), so the expression will return false.

const names = ['Ram', 'Rohan'];
const isEmpty = !names.length; // false

As with the first method, there are some things to remember when using this approach, which we will review next.

3. Applying the Array.isArray() method

While using the length property can help check if a JavaScript array is empty, it must only sometimes be a reliable strategy since other JavaScript objects also have a length property. So, before we check the length of an array, we must first check that it is an array.

One option is to use the Array.isArray() method in conjunction with the length property check. This method checks whether a variable is an array, giving us more confidence in our code.

Here's how you can use it:

const names = [];
Array.isArray(names) && names.length === 0; // true

Using Array.isArray() helps ensure we deal with an array.

For example, if we have a JavaScript object like this:

const names = {
length: 0,
};

Checking its length directly would wrongly indicate it's empty.

names.length === 0; // true

But using Array.isArray() gives us a more accurate result:

Array.isArray(names) && names.length === 0; // false

Plus, Array.isArray() can filter out array-like objects such as NodeList.

const nodes = document.querySelectorAll('div');
Array.isArray(nodes) && nodes.length === 0; // false

So, while Array.isArray() does not directly reveal whether an array is empty.

It does confirm that we are working with an array, which boosts our confidence in our tests.

4. Gotcha: Applying the === [] syntax

When attempting to check if a JavaScript array is empty, a standard error is to use === [] as you would in PHP.

However, in JavaScript, this approach will always return false.

Using === [] to check if an array with items is empty will correctly return false.

const names = ['Ram', 'Rohan'];
names === []; // false

Even if you use === [] to check if an empty array is empty, the result is false:

const names = [];
names === []; // false

This is because arrays in JavaScript are objects. So, when you use === [], you compare their identities rather than their values.

For example:

const names = ['Ram', 'Rohan'];
names === names; // true

In this code, we are comparing the identity of the name array to itself.

Because it is the same array, it returns true.

However, when we try to compare it to another array with the same values,

const names = ['Ram', 'Rohan'];
names === ['Ram', 'Rohan']; // false

It returns false because they are different arrays despite having the same values.

Why Handling Empty Arrays Matters

Empty arrays are easily overlooked but handling them correctly is a point of insurance policy for productive web applications. What if a form with a submit button isn't activating because the code erroneously believes there's data in an empty array? These petty problems catch the users off balance which is a backward way to lead your application out of the estimated result.

The Role of Array.isArray()

JavaScript comes with an Array.isArray() method that helps you easily determine if a variable is an array. Therefore, the variable doesn't have to be confused with null, undefined, or other types which are not arrays. This will guarantee you that your code functions with the desired effect.

Why Not Just Check the Length Property?

If you are wondering about the possibility of not using the length property only to check if an array is empty, then your thinking is justified. The problem is that other data types, such as strings, also have a length property, which can result in you presuming an array.

Example: length Property with Strings

const string = 'Hello World';
console.log(string.length); // Output: 11
console.log(Array.isArray(string)); // Output: false

In this example, the length property for a string tells us the number of characters, whereas Array.isArray() confirms it’s not an array.

Why This Matters

  • Shared Property, Different Meanings: Both strings and arrays have a length property by their nature, but you may use it for different purposes. In strings, length equals characters, and in arrays, it counts elements (even empty slots in case of sparse arrays).
  • Know Your Data Type: The length property tells you how many items you have — whether you are using a string, an array, or an array-like object (NodeList or arguments object) will affect how you use it. For example, if you are dealing with a collection of elements, it will be very important to know if the elements in your collection are actually an array or some other structure. This knowledge will have an effect on the way you will iterate and convert it in case it is needed.
  • More Than Just Length: This underpins a fundamental point in JavaScript: knowing the type and shape of your data alongside knowing the properties and methods at your disposal is equally as important. The length property is handy, yet what you choose to do with it is determined by whether your string, array, or array-like object.

We also write a blog for Check If an Array Is Empty in PHP. You can also learn many development-related gigs from our blog page.

Also Read: 4 Easy Ways to Check If an Array Is Empty in PHP

Essence

These methods can help you Check Empty Array in JavaScript. We prepared this guide for developers who need help with the common issue of finding an empty array in JavaScript. Elightwalk Technology offers a variety of solutions for developers and businesses to learn, update, and create new websites using leading solution formulas. Contact us if you have any technological questions or need guidance on developing related solutions. Our development team assists you and guides you to the right solution for your projects.

Pravin Prajapati
Full Stack Developer

Expert in frontend and backend development, combining creativity with sharp technical knowledge. Passionate about keeping up with industry trends, he implements cutting-edge technologies, showcasing strong problem-solving skills and attention to detail in crafting innovative solutions.

Most Visited Blog

4 Easy Ways to Check If an Array Is Empty in PHP
We explore the typical checking situation to see if a PHP array is empty. We provide clear explanations and examples for each approach. Whether you're a beginner or a seasoned developer, these techniques will equip you to handle empty arrays in your PHP codebase effectively.
How to Perform Simple CRUD with PHP and MySQL
Learn the fundamentals of using PHP and MySQL for CRUD operations. From single query execution to prepared statements, this guide will teach you everything you need to know to build dynamic web applications that interact with your database seamlessly. Whether you're a beginner or an experienced programmer, learn the fundamentals of developing dynamic web applications and efficiently manipulating database data.
How to delete all products and categories in Magento
Manage your Magento database with a SQL script to delete all categories and products. Prioritise backups, test in a controlled environment and follow best practices for responsible and secure usage.