In this section, we are going to learn about whether the array is null or empty, or undefined. We will use JavaScript to do this. Sometimes the unexpected output or software crashes is occurred by the empty or null array. If we want to avoid this type of situation, we have to check whether the given or defined array is null or empty. We will also check that the array is undefined or not.
If condition and array’s length will be very useful to check the array. The number of elements is returned or set by the length property in the array. On the basis of the number of elements, we can understand that the array is empty or not. If the defined or given array is empty, it will contain the 0 elements. In our example, we will describe more than one example to understand them easily. The very simple example to check that the array is null or empty or undefined is described as follows:
if (ourArray && ourArray.length > 0) {
console.log('ourArray shows not empty.');
}else{
console.log('ourArray shows empty.');
}
In the below example, we will check the JQuery array if it is empty. The code to do this is as follows:
Example:
<!DOCTYPE html>
<html>
<head>
<title> JavaScript - Check array is empty or undefined or null </title>
</head>
<body>
<script type="text/javascript">
/*
Basic Array checking using JQuery
*/
var ourArray = [1, 2, 3];
if (ourArray && ourArray.length > 0) {
console.log('ourArray shows not empty');
}else{
console.log('ourArray shows empty.');
}
/*
Empty array checking using Jquery Array
*/
var ourArray2 = [];
if (ourArray2 && ourArray2.length > 0) {
console.log('ourArray2 shows not empty.');
}else{
console.log('ourArray2 shows empty.');
}
/*
Undefined array checking using JQuery Array
*/
if (typeof ourArray3 !== 'undefined' && ourArray3.length > 0) {
console.log('ourArray3 shows not empty.');
}else{
console.log('ourArray3 shows empty.');
}
/*
Null array checking using Jquery Array
*/
var ourArray4 = null;
if (ourArray4 && ourArray4.length > 0) {
console.log('ourArray4 is not empty.');
}else{
console.log('ourArray4 is empty.');
}
</script>
</body>
</html>
Now our above code is ready, and we can run it. When we run this, the following output will be generated:
ourArray shows not empty.
ourArray2 shows empty.
ourArray3 shows empty.
ourArray4 shows empty.
Leave a Review