jquery check if array is empty

Posted by w3diy - 4 months ago

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

<!DOCTYPE html>
<html>
<head>
    <title>How to check if array is empty or null or undefined in javascript? - w3diy.com</title>
</head>
<body>

<script type="text/javascript">

    /*
      Basic Checking for Jquery Array
    */

    var playerList = [1, 2, 3];



    if (playerList && playerList.length > 0) {
        console.log('playerList is not empty.');
    }else{
        console.log('playerList is empty.');

    }

    /*
      Basic Checking with empty array for Jquery Array
    */

    var playerList2 = [];
    if (playerList2 && playerList2.length > 0) {
        console.log('playerList2 is not empty.');
    }else{
        console.log('playerList2 is empty.');
    }

    /*
      Basic Checking with undefined array for Jquery Array
    */

    if (typeof playerList3 !== 'undefined' && playerList3.length > 0) {
        console.log('playerList3 is not empty.');
    }else{

        console.log('playerList3 is empty.');
    }

    /*
      Basic Checking with null array for Jquery Array
    */

    var playerList4 = null;

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

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

    }else{

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

    }

</script>
</body>
</html>

Results:

playerList is not empty.

playerList2 is empty.

playerList3 is empty.

playerList4 is empty.