array
empty
programming
data validation

How can I check whether an array is null / empty?

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

In programming, particularly in JavaScript, checking whether an array is null or empty is a common task that you might encounter often. Understanding how to perform these checks efficiently can be critical in ensuring that your code runs smoothly without errors. In this article, we'll explore the methods for checking if an array is null or empty, including technical explanations and examples.

What is an Array?

Before diving into checks, it's essential to understand what an array is. An array is a data structure used to store multiple values in a single variable. It can hold different types of data, such as numbers, strings, or even other arrays. In most programming languages, arrays have a fixed size; however, in JavaScript, arrays are dynamic and can grow as needed.

Null vs. Empty Arrays

  1. Null Array: A null array means that the array has not been instantiated or assigned any memory space. It does not point to any actual array structure.
  2. Empty Array: An empty array is an array that has been instantiated but contains no elements.

How to Check for Null or Empty Arrays

Checking for Null

Checking whether an array is null involves ensuring that the array variable points to a valid memory location. In JavaScript, you can use a simple conditional statement:

javascript
if (arrayVariable === null) {
  console.log("The array is null.");
}

Checking for Empty

Once you've established that an array is not null, you can check if it is empty by examining its length property:

javascript
if (arrayVariable.length === 0) {
  console.log("The array is empty.");
}

Combined Check for Null or Empty

A more comprehensive approach is to combine the null and empty checks in a single statement:

javascript
if (!arrayVariable || arrayVariable.length === 0) {
  console.log("The array is either null or empty.");
}

Here, the first condition checks if the array is null or undefined using the logical NOT operator (!), and the second condition checks if the array's length is zero.

Dealing with Undefined Arrays

Sometimes, an array might be undefined rather than null. Undefined is another primitive type in JavaScript, indicating that a variable has not been assigned a value. To check for undefined arrays, you can extend the combined check:

javascript
1if (
2  typeof arrayVariable === "undefined" ||
3  arrayVariable === null ||
4  arrayVariable.length === 0
5) {
6  console.log("The array is either undefined, null, or empty.");
7}

Additional Considerations

  • Falsy Values: In JavaScript, null, undefined, 0, and empty strings are considered falsy values. Therefore, using a simple truthy/falsy check can sometimes suffice.
  • Loose Equality: Using == instead of === can yield strange results due to type coercion. It's better to use strict equality === unless you understand the implications.

Example Code Snippet

Here's a comprehensive code snippet that checks for null, undefined, or empty arrays:

javascript
1function isArrayNullOrEmpty(arr) {
2  if (!arr || arr.length === 0) {
3    return true;
4  }
5  return false;
6}
7
8let arr1 = null;
9let arr2;
10let arr3 = [];
11let arr4 = [1, 2, 3];
12
13console.log(isArrayNullOrEmpty(arr1)); // true
14console.log(isArrayNullOrEmpty(arr2)); // true
15console.log(isArrayNullOrEmpty(arr3)); // true
16console.log(isArrayNullOrEmpty(arr4)); // false

Key Points Summary

Below is a table summarizing the key points for checking null and empty arrays:

ConditionDescription
arr === nullChecks if the array is explicitly null.
typeof arr === 'undefined'Checks if the array is undefined.
arr.length === 0Checks if the array is empty (contains no elements).
!arrChecks if the array is falsy (null, undefined, etc.).
!arr | | arr.length === 0Combined check for null/undefined or empty arrays.
typeof arr === 'undefined' | | arr === null | | arr.length === 0Best practice for comprehensive checking.

By employing the strategies and techniques outlined in this article, you can effectively manage arrays in your applications, ensuring that they are neither null nor empty when performing operations. Proper array checks can prevent runtime errors and ensure robust code execution.


Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.