Javascript check if array is empty example; In this tutorial you will learn how to check whether an array is empty or not in JavaScript;
In Js you can use the .length property to check if an array is empty or not. Let’s run through some examples.
Example 1:
If an array’s length is equal to 0, then it is empty. If the array’s length is greater than 0, it isn’t empty.
const arr = ['coding'];
if (arr.length > 0) {
console.log('arr is not empty')
}
Example 2:
If you’re unsure whether the variable stores an array, you can check for the type of its value before accessing its length property.
let arr = ['coding'];
if (Array.isArray(arr) && arr.length > 0) {
console.log('arr is not empty')
}
Example 3:
You can check the type of its value is not undefined before accessing its length property.
const arr = ['coding'];
if (typeof arr !== 'undefined' && arr.length > 0) {
console.log('arr is not empty')
}
Example 4:
Alternatively, you can use optional chaining operator ?. to avoid an error if variable storing the array is set to undefined
or null
.
// Not supported in IE 6-11
const arr = ['coding'];
// Use ?.
if (arr?.length > 0) {
console.log('arr is not empty')
}
In this article, we learned that you can use the length
property in JavaScript in various ways to check if an array is empty or not. The length
property returns the number of items in an array.