Check Whether an Array Is Empty

How to check if array is empty or does not exist?

You want to do the check for undefined first. If you do it the other way round, it will generate an error if the array is undefined.

if (array === undefined || array.length == 0) {
// array does not exist or is empty
}

Update

This answer is getting a fair amount of attention, so I'd like to point out that my original answer, more than anything else, addressed the wrong order of the conditions being evaluated in the question. In this sense, it fails to address several scenarios, such as null values, other types of objects with a length property, etc. It is also not very idiomatic JavaScript.

The foolproof approach

Taking some inspiration from the comments, below is what I currently consider to be the foolproof way to check whether an array is empty or does not exist. It also takes into account that the variable might not refer to an array, but to some other type of object with a length property.

if (!Array.isArray(array) || !array.length) {
// array does not exist, is not an array, or is empty
// ⇒ do not attempt to process array
}

To break it down:

  1. Array.isArray(), unsurprisingly, checks whether its argument is an array. This weeds out values like null, undefined and anything else that is not an array.

    Note that this will also eliminate array-like objects, such as the arguments object and DOM NodeList objects. Depending on your situation, this might not be the behavior you're after.

  2. The array.length condition checks whether the variable's length property evaluates to a truthy value. Because the previous condition already established that we are indeed dealing with an array, more strict comparisons like array.length != 0 or array.length !== 0 are not required here.

The pragmatic approach

In a lot of cases, the above might seem like overkill. Maybe you're using a higher order language like TypeScript that does most of the type-checking for you at compile-time, or you really don't care whether the object is actually an array, or just array-like.

In those cases, I tend to go for the following, more idiomatic JavaScript:

if (!array || !array.length) {
// array or array.length are falsy
// ⇒ do not attempt to process array
}

Or, more frequently, its inverse:

if (array && array.length) {
// array and array.length are truthy
// ⇒ probably OK to process array
}

With the introduction of the optional chaining operator (Elvis operator) in ECMAScript 2020, this can be shortened even further:

if (!array?.length) {
// array or array.length are falsy
// ⇒ do not attempt to process array
}

Or the opposite:

if (array?.length) {
// array and array.length are truthy
// ⇒ probably OK to process array
}

How to check if an array is empty or exists?

if (typeof image_array !== 'undefined' && image_array.length > 0) {
// the array is defined and has at least one element
}

Your problem may be happening due to a mix of implicit global variables and variable hoisting. Make sure you use var whenever declaring a variable:

<?php echo "var image_array = ".json_encode($images);?>
// add var ^^^ here

And then make sure you never accidently redeclare that variable later:

else {
...
image_array = []; // no var here
}

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

There's a key difference between a null array and an empty array. This is a test for null.

int arr[] = null;
if (arr == null) {
System.out.println("array is null");
}

"Empty" here has no official meaning. I'm choosing to define empty as having 0 elements:

arr = new int[0];
if (arr.length == 0) {
System.out.println("array is empty");
}

An alternative definition of "empty" is if all the elements are null:

Object arr[] = new Object[10];
boolean empty = true;
for (int i=0; i<arr.length; i++) {
if (arr[i] != null) {
empty = false;
break;
}
}

or

Object arr[] = new Object[10];
boolean empty = true;
for (Object ob : arr) {
if (ob != null) {
empty = false;
break;
}
}

Check if array is empty or includes the value, typescript

Acctually, array is a reference type. When you would like to check it with [ ], they aren't equal. They're totally different, it's better to check this condition with length. So based on your code you should do something like this :

if (!testArray || testArray.length == 0 || testArray.includes(value)) {
// do something
}

How to check whether an array is empty using PHP?

If you just need to check if there are ANY elements in the array, you can use either the array itself, due to PHP's loose typing, or - if you prefer a stricter approach - use count():

if (!$playerlist) {
// list is empty.
}
if (count($playerlist) === 0) {
// list is empty.
}

If you need to clean out empty values before checking (generally done to prevent explodeing weird strings):

foreach ($playerlist as $key => $value) {
if (!strlen($value)) {
unset($playerlist[$key]);
}
}
if (!$playerlist) {
//empty array
}

How to check if array of object is empty?

You can do something like this

 cities = this.state.city_name;  arr = cities.length;  if(arr == 0) {     console.log('no result found')       }  else {     console.log(cities)       }

How do I check if a list is empty?

if not a:
print("List is empty")

Using the implicit booleanness of the empty list is quite Pythonic.

how to check for an empty array java

In array class we have a static variable defined "length", which holds the number of elements in array object. You can use that to find the length as:

if(arrayName.length == 0)
System.out.println("array empty");
else
System.out.println("array not empty");

Why can't I check if an array is empty with array == []?

The problem is that arrays are objects. When you compare two objects, you compare their references. Per the MDN documentation:

Equality (==)

If both operands are objects, then JavaScript compares internal references which are equal when operands refer to the same object in memory.

Since two instances of arrays don't necessarily have the same reference, the check fails. Just try this in the console:

> [] == []
false

Two arrays seemingly with the same content (or lack thereof) are not equal. That's because content is not checked, but reference. These two arrays are separate instances and refer to different places in memory, thus the check evaluates to false.

On the other hand, just checking the length, and if it is zero checks if the array is empty or not. The length property signifies the amount of content in an array1 and is part of every array. Since it is part of every array and reflects the amount of data in the array, you can use it to check if the array is empty or not.


1 Beware, though, of sparse arrays as mentioned by RobG in the comments. Such arrays can be created with new Array(N) which will give you an empty array, but with length N.



Related Topics



Leave a reply



Submit