Check if an array is empty or null in Javascript

Posted by

I’ll assist you if you require jQuery to determine whether an array is empty or undefined. Javascript makes it simple to determine whether an array is empty or not. We’ll examine the length of the array and use a straightforward if condition. In JavaScript, we can quickly determine whether an array is empty, null, or undefined.

I’ll offer you a straightforward example here with a variety of scenarios, so you can choose from any of them. I’ll advise you to use this one as the simple code below:

if (myArray && myArray.length > 0) {

   console.log('myArray is not empty.');

}else{

   console.log('myArray is empty.');

}

You can also see a complete example of a jQuery array being checked for emptyness below. So let’s run the code below and examine the output, which I’ve included below:

Example:

<!DOCTYPE html>
<html>
<head>
    <title>How to check if array is empty or null or undefined in javascript?</title>
</head>
<body>
  
<script type="text/javascript">
   
    /*
      Basic Checking for Jquery Array
    */
    var myArray = [1, 2, 3];
  
    if (myArray && myArray.length > 0) {
        console.log('myArray is not empty.');
    }else{
        console.log('myArray is empty.');
    }
  
  
    /*
      Basic Checking with empty array for Jquery Array
    */
    var myArray2 = [];
  
    if (myArray2 && myArray2.length > 0) {
        console.log('myArray2 is not empty.');
    }else{
        console.log('myArray2 is empty.');
    }
  
  
    /*
      Basic Checking with undefined array for Jquery Array
    */
    if (typeof myArray3 !== 'undefined' && myArray3.length > 0) {
        console.log('myArray3 is not empty.');
    }else{
        console.log('myArray3 is empty.');
    }
  
  
    /*
      Basic Checking with null array for Jquery Array
    */
    var myArray4 = null;
   
    if (myArray4 && myArray4.length > 0) {
        console.log('myArray4 is not empty.');
    }else{
        console.log('myArray4 is empty.');
    }
   
</script>
</body>
</html>

Output:

myArray is not empty.

myArray2 is empty.

myArray3 is empty.

myArray4 is empty.
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x