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 Create virtual environment in Python3
Python virtual environment is tool that...jQuery get Value of Selected Radio Button
jQuery radio button is used when you wan...Laravel 8 Create Custom Service Provider Example
In Laravel application, you have noticed...How To Set up SSH Keys on a Linux Server
SSH or Secure Shell is network protocol...Upload Single and Multiple Images with Preview in React with Example
Today in this React image upload preview...