Check if array is empty ReactJS

Looking to check if your array is empty in ReactJS? Here’s how to do so.


First, let’s create a simple array with numbers inside. It will look something like this:

var numberOfProducts = [10, 12, 7, 5, 10];

Let’s log it in the console so that we can get the initial length of how many items are in the array:


We are told that there are 5 items in the array. You can count them if you want.

Now, our next task is that we want to check if our array is empty. And, we can do that by creating a function. For this specific case, I created a function that says that if the amount of items in the array is less than four, to leave it alone, but if the amount of items in the array is more than four, to return an empty array.


The function will look something like this:

function removeProducts() {
    if (numberOfProducts.length < 4) {
    } else if (numberOfProducts.length >= 4) {
      numberOfProducts = []

And of course, call the function at the end to execute it. Now, let’s log the result in the console and see the length of our array now.


We are told that the length in the array is now 0. Our function worked!

So, you can check to see if an array is empty by using the .length property.

React is a great framework to use, especially because you can write your HTML and JS in the same page, as well as use components and hooks.

Why would you need to check to see if the length in an array is empty?

One reason for doing so would be like the reason that we did in this blog article. You might have an array of numbers, but if certain conditions don’t meet, you have the ability to empty what you need out of the array. And of course, use the console to see what’s still inside.

Other recommended articles for developers:

What is React Hooks? With Example

For designers:

What is the UX Design process?

For business owners:

How to improve website accessibility


Posted in:

Leave a Reply

%d bloggers like this: