clock  Mon - Sun 8.00 AM - 8.00 PM
mail  edu@teknowize.com
fb
instagram
play store
pinterest

How To Check If Array Is Empty Or Null Or Undefined Using Javascript

  Sumit Dey Sarkar
  24 Aug 2022
  JavaScript
Imperial Advance Hero Image

How To Check If Array Is Empty Or Null Or Undefined Using Javascript

In this tutorial we will learn how to check if array is empty or null or undefined using javascript.

Here well will see all three conditions one by one.

Let's see examples -

1) How to check if array is empty or null or undefined using javascript (Basic Cheking)

<!DOCTYPE html>
<html>

<head>
    <title>How to check if array is empty or null or undefined using javascript</title>
</head>

<body>

    <script type="text/javascript">

        var myArray = [1, 2, 3];

        if (myArray && myArray.length > 0) {
            alert('myArray is not empty.');
        } else {
            alert('myArray is empty.');
        }

    </script>
</body>

</html>

 

Output

javascript

 

2) How to check if array is empty using javascript

<!DOCTYPE html>
<html>

<head>
    <title>How to check if array is empty or null or undefined using javascript</title>
</head>

<body>

    <script type="text/javascript">

       var myArray = [];

        if (myArray && myArray.length > 0) {
            console.log('This array is not empty.');
        } else {
            alert('This array is empty.');
        }

    </script>
</body>

</html>

 

Output

javascript

 

3) How to check if array is null using javascript

<!DOCTYPE html>
<html>

<head>
    <title>How to check if array is empty or null or undefined using javascript</title>
</head>

<body>

    <script type="text/javascript">

  var myArray = null;

        if (myArray && myArray.length > 0) {
            console.log('This array is not null.');
        } else {
            alert('This array is null.');
        }

    </script>
</body>

</html>

 

Output

javascript

 

4) How to check if array is undefined using javascript

<!DOCTYPE html>
<html>

<head>
    <title>How to check if array is empty or null or undefined using javascript</title>
</head>

<body>

    <script type="text/javascript">

        var myArray = [1, 2, 3];

        if (myArray && myArray.length > 0) {
            alert('myArray is not empty.');
        } else {
            alert('myArray is empty.');
        }

    </script>
</body>

</html>

 

Output

javascript