In this segment, we will explore how to determine if an array is null, empty, or undefined using JavaScript. Frequently, software failures or unexpected results can stem from encountering an empty or null array. To prevent such issues, it is essential to verify whether the specified array is indeed null or devoid of elements. Additionally, we will assess whether the array is undefined.
Utilizing conditions alongside the length of an array proves to be highly beneficial for examining its contents. The length property of an array provides the count of elements it holds, allowing us to determine whether the array is populated or devoid of elements. An array that is either declared or provided as empty will have a length of 0 elements. In the following sections, we will present multiple examples to facilitate a clearer understanding. The most straightforward illustration for verifying whether an array is null, empty, or undefined is outlined below:
if (ourArray && ourArray.length > 0) {
console.log('ourArray shows not empty.');
}else{
console.log('ourArray shows empty.');
}
In the following illustration, we will verify whether the JQuery array is devoid of elements. The code necessary to accomplish this task is presented below:
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>
At this point, our previously discussed code is prepared for execution, and we can proceed to run it. Upon executing the code, the following output will be produced:
ourArray shows not empty.
ourArray2 shows empty.
ourArray3 shows empty.
ourArray4 shows empty.