When working in Javascript, many times you need to check if array is empty or undefined. This needs to check when you want to loop the array, so it doesn't return error.
There are lot of ways to check if Javascript array is empty or not. Here are some examples:
The first way to check is to get array length. If the array length is 0, then it empty array.
<script type="text/javascript">
var newArray = [1];
if (newArray && newArray.length > 0) {
// newArray is not empty
} else {
// newArray is empty
}
</script>
Sometimes you also want to check that array should not be undefined object and has at least one element. This can be also check 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 also use JQuery isEmptyObject method to check whether array is empty or contains elements. This is reliable method.
<script src="https://code.jquery.com/jquery-3.5.0.min.js"></script>
<script type="text/javascript">
var newArray1 = [1, 2, 3];
var newArray2 = [];
console.log(jQuery.isEmptyObject(newArray1)); // returns false
console.log(jQuery.isEmptyObject(newArray2)); // returns true
</script>
This way you can check wether array contains element or is empty. I hope this article will help you a little.
Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]
How to get the values of selected checkboxes in a group using jQuery
Use the jQuery :checked select...jQuery val method
In this article, we will learn how you c...How to Convert JS Object to JSON String
Use the JSON.stringify() Method You c...VueJs CRUD Example using MongoDB | Express.js | Vue.js | Node.js
This is a step by step MEVN stack tutori...How to Insert and fetch fullcalendar events from mysql database ?
Hello to all, welcome to therichpost.com...