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

AuthorSumit Dey Sarkar

Pubish Date24 Aug 2022

categoryJavaScript

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

Comments 0

Leave a comment