In this example, I will show you how to check if an array is empty or null in javascript or jquery. When we are working in javascript and you want to loop the array at that time we need to check whether an array is empty or not. So, it doesn't return an error. There are many ways to check javascript array is empty or not.
So, let's see how to check if the array contains a value in jquery or jquery check if the value exists in an array of objects.
This method is reliable to check whether the array is empty or contains elements.
<script src="https://code.jquery.com/jquery-3.5.0.min.js"></script>
<script type="text/javascript">
var Array1 = [1, 2, 3];
var Array2 = [];
console.log(jQuery.isEmptyObject(Array1)); // returns false
console.log(jQuery.isEmptyObject(Array2)); // returns true
</script>
Many times we are required to check that array should not be an undefined object and has at least one element. This can be also checked with typeof.
<script type="text/javascript">
var undefinedAray = undefined;
if (typeof undefinedAray !== "undefined" && undefinedAray.length > 0) {
// undefinedAray is not empty
} else {
// undefinedAray is empty or undefined
}
</script>
We can check the array with length, if the array length is 0 then the array is empty.
<script type="text/javascript">
var Arraylegnth = [1];
if (Arraylegnth && Arraylegnth.length > 0) {
// Arraylegnth is not empty
} else {
// Arraylegnth is empty
}
</script>
You might also like:
Hello developers! Today, we're about to embark on a journey to elevate our Laravel applications by integrating...
Feb-12-2024
In this tutorial I will teach you the most important topic of how to integrate the PayPal payment gateway in larave...
Jul-22-2020
In this tutorial, I will show you how to create a CRUD operation with login-logout in PHP. So, if you are a newcomer in...
Jul-20-2020
In this article, we will see laravel whereBetween query example. SQL provides many different types of methods or qu...
Jan-13-2021