How to check array is empty or null or undefined in javascript?

Share Me
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Today in this I will show you how to check a array empty or undefined. If you need for jquery check if a array is empty or undefined then here i will help you. So you can easily check if a array is empty or not by using javascript. Now we will use simple if condition and also length of array with checking. So now we can easily check array is empty or null in javascript.

So here i will give you a very simple example with multiple cases so you can use any one from there on your project. I will suggest you that you can use this one as bellow as simple code:

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

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

}else{

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

}

You can also see here a bellow full example for checking jquery array if conditions empty. So let’s use bellow code and also check output as i attached bellow:

<!DOCTYPE html>
<html>
<head>
    <title>How to check if array is empty or null or undefined in javascript? - Codingspoint.com</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

Read Also: Javascript – Convert Array into Comma Separated String Example

I hope it will help you.For more you can follow us on facebook

About Shahriar Sagor

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by Shahriar Sagor →