javascript-array-is-empty-or-not

How to check if an array is empty or not using javascript

While developing any application, an array is mostly used variable to store the list of values. And in most of the scenarios, you might want to show the data or message based on the array value.

If an array is empty you might want to show a message like “No data found” and when there are values in it you’ll iterate through it and values will be displayed.

Here I’ll show you how can you check if array is empty or array has a value.

Let’s take an example of a list of users so we’ll create a variable called users and you can think of this 4 possibilities of value that users can have.

  1. users = ['Rob', 'Foo', 'Dod'];
  2. users = [ ];
  3. users = undefined;
  4. users = null;

You can check if array is empty or not using the following condition.


let users = [];
if (users && users.length > 0) {
  console.log("users array contains a value");
} else {
  console.log("users array is empty");
}
//OUTPUT: users array is empty

The output for above 4 possibilities will look as follows:

  1. users = [‘Rob’, ‘Foo’, ‘Dod’];  //OUTPUT: users array contains a value.
  2. users = [ ];  //OUTPUT: users array is empty.
  3. users = undefined;  //OUTPUT: users array is empty.
  4. users = null;  //OUTPUT: users array is empty.

You can see the full code here:


<!DOCTYPE html>
<html>
<body>

<h1>How to check if an array is empty or not using javascript</h1>


<script>
//Case 1: When users array contanins multiple values
let users = [1,2,3];
if (users && users.length > 0) {
  console.log("users array contains a value");
} else {
  console.log("users array is empty");
}
//OUTPUT: users array contains a value


//Case 2: When users array contanins no values
let users = [];
if (users && users.length > 0) {
  console.log("users array contains a value");
} else {
  console.log("users array is empty");
}
//OUTPUT: users array is empty

//Case 3: When users is null
let users = null;
if (users && users.length > 0) {
  console.log("users array contains a value");
} else {
  console.log("users array is empty");
}
//OUTPUT: users array is empty

//Case 4: When users is undefined
let users = undefined;
if (users && users.length > 0) {
  console.log("users array contains a value");
} else {
  console.log("users array is empty");
}
//OUTPUT: users array is empty
</script> 

</body>
</html> 

If you want to check if users is a strictly empty array (not null or not undefined or not an array), you can use the following if condition.

let users = [];
if (users && users.constructor === Array) {
  if (users.length > 0) {
    console.log("users array contains a value");
  } else {
    console.log("users array is a strictly an empty array");
  }
} else {
  console.log("users array is either null or undefined or not an array");
}
//OUTPUT:users array is a strictly an empty array

I hope this would help and if it’s don’t forget to share this article.

Also Read: