How to check if Array is empty or NULL in JavaScript?
In this tutorial, you will learn how to check if Array is empty or NULL in JavaScript. When we are working woth loops that time may we need to check if array is empty or not before looping on the array.
There are many ways to check empty array in JavaScript and jQuery as well. Javascript provides in-built function as well to check the array is empty or not. So let's get started with few examples.
- Using isEmptyObject()
- Using length
How to check if an array is empty using isEmptyObject()
isEmptyObject is jQuery a function that is reliable to check array is empty or not.
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
<script>
var Array1 = [1, 2, 3];
var Array2 = [];
console.log(jQuery.isEmptyObject(Array1)); // returns false
console.log(jQuery.isEmptyObject(Array2)); // returns true
</script>
How to check if an array is empty using length?
We can check if array is empty or not with array length method. If array length returns 0 it means array is empty.
<script>
var Arraylegnth = [1];
if (Arraylegnth.length > 0) {
// Array is not empty
} else {
// Array is empty
}
</script>
I hope it will help you.
Happy Coding :)