In this tutorial, you will find some built-in methods how to check if an array or object is empty in React JS applications.
How to Check if Array or Object is Empty in React Js
Here are some built-in methods that allow users to check whether an array or object is empty or not:
Method 1: Using the length property
The most common and simple way to check if an array or object is empty is to use the .length
property, Here’s an example:
const myArray = [];
if (myArray.length === 0) {
console.log('Array is empty');
} else {
console.log('Array is not empty');
}
Method 2: Using the every() method
The each() method tests whether all elements in an array satisfy a certain condition. If the array is empty, the each() method returns true, Here’s an example:
const myArray = [];
if (myArray.every(item => Object.keys(item).length === 0)) {
console.log('Array is empty');
} else {
console.log('Array is not empty');
}
Method 3: Using the filter() method
The filter() method creates a new array with all elements that satisfy a certain condition. If the array is empty, the filter() method returns an empty array, Here’s an example:
const myArray = [];
if (myArray.filter(item => item !== null).length === 0) {
console.log('Array is empty');
} else {
console.log('Array is not empty');
}
Method 4: Using the some() method
The some() method tests whether at least one element in an array passes a certain position. If the array is empty, the some() method returns false, Here’s an example:
const myArray = [];
if (myArray.some(item => item !== null)) {
console.log('Array is not empty');
} else {
console.log('Array is empty');
}
Conclusion
In this tutorial, you have explored four different ways to check if an object array is empty in React.