JS - How to Check if Array is Empty or Null or Undefined or has 3 items

Published on Aug 17, 2022

Hello dev's, today I'll show you how to check if array is empty or null or undefined or has 3 items using Pure JS. We all know that sometimes handling array is getting quite complex in our JS script code. And it is very important to handle each case in our JS code because one line of code can make whole site unstable. So todays tutorial is regarding handling array. So, let's get started.

Checking Array

So here we'll see 3 example which will cover all most all the known use cases array. So in the first array we'll see If an array is empty or not, And in the 2nd example we'll see if an array has 0 items or not. And in the third example we'll see if an array is undefined or not. And in the last example we'll see if an array is null or not. So let's start our coding. See the below conde snippets.

<html>
<head>
    <title>How to check if array is empty or null or undefined or has 0 items in javascript - shouts.dev</title>
</head>
<body>
  
<script>
    var array = [1, 2, 3];
  
    if (array && array.length > 0) {
        console.log('array has '+array.length+' items');
    }else{
        console.log('array is empty.');
    }
  
  
    /*
      Checking if array is empty
    */
    var array2 = [];
  
    if (array2 && array2.length > 0) {
        console.log('array3 has'+array2.length+'items');
    }else{
        console.log('array2 is empty.');
    }
  
    /*
      Checking if array is undefined
    */
    if (typeof array3 !== 'undefined' && array3.length > 0) {
        console.log('array3 has'+array3.length+'items');
    }else{
        console.log('array3 is empty.');
    }
  
  
    /*
      Basic Checking with null array for Jquery Array
    */
    var array4 = null;
   
    if (array4 && array4.length > 0) {
        console.log('array4 has'+array4.length+'items');
    }else{
        console.log('array4 is empty.');
    }
   
</script>
</body>
</html>

That's it for today. If you've any question, catch me in the comment section. Hope you'll enjoy through this tutorial. Thanks for reading :)

Comments (0)