JavaScript Function To Check Array Is Empty Or Not Example

Nov 02, 2021 . Admin



Hello Friends,

Now let's see example of how to check array is empty or not example. We will use how to check array is empty or not in javascript. Here you will learn how to check array is empty or not. Let's get started with how to check array is empty or not in javascript.

Here i will give you many example how to check array is empty or not javascript.

Example : 1
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>JavaScript Function To Check Array Is Empty Or Not Example - MyWebtuts.com</title>
    </head>
    <body>
        <h2>JavaScript Function To Check Array Is Empty Or Not Example - MyWebtuts.com</h2>
        
        <script type="text/javascript">
            var t1 = [54, 56, 29, 37];  
            var t2 = [];  

            if(t1.length == 0)  
                document.write("array 1 is empty <br>");  
            else   
                document.write("array 1 is not empty <br>");  

            if(t2.length == 0)  
                document.write("array 2 is empty <br>");  
            else   
                document.write("array 2 is not empty <br>");    
        </script>
    </body>
</html>
Output :
array 1 is not empty
array 2 is empty
Example : 2
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>JavaScript Function To Check Array Is Empty Or Not Example - MyWebtuts.com</title>
    </head>
    <body>
        <h2>JavaScript Function To Check Array Is Empty Or Not Example - MyWebtuts.com</h2>
        
        <script type="text/javascript">
            var a1 = [];  
            var a2 = "notAnArray";  

            if(Array.isArray(a1) == true){  
                document.write("array 1 is an array");  
            if (a1.length <= 0)  
                document.write(" and it is empty <br>");  
            else   
                document.write(" and it is not empty. <br>");  
            }  
            else  
                document.write("array 1 is not an array. <br>");  

            if(Array.isArray(a2) == true){  
                document.write("array 2 is an array");  
                
                if (a2.length <= 0)  
                    document.write(" and it is empty as well. <br>");  
                else   
                    document.write(" and it is not empty. <br>");  
            }  
            else  
            document.write("array 2 is not an array. <br>");      
        </script>
    </body>
</html>
Output :
array 1 is an array and it is empty
array 2 is not an array.

It will help you...

#Javascript