Check if an Array is Empty in React

avatar

Borislav Hadzhiev

Mon Apr 25 20222 min read

Check if an Array is Empty in React #

To check if an array is empty in React, access its length property, e.g. arr.length. 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.

App.js
import {useEffect, useState} from 'react'; export default function App() { const [messages, setMessages] = useState([]); useEffect(() => { if (messages.length > 0) { console.log('array is NOT empty'); } if (messages?.length > 0) { console.log('array is NOT empty'); } if (messages.length === 0) { console.log('array is empty'); } }, [messages]); return ( <div> <h2>Array: {JSON.stringify(messages)}</h2> <button onClick={() => setMessages(current => [...current, 'hello'])}> Add message </button> </div> ); }

check if array is empty

The first if statement checks whether the array's length is greater than 0.

The if block will only run if the array isn't empty.

The second if statement uses the optional chaining (?.) operator to avoid an error if the reference is nullish (null or undefined).

App.js
const arr = ['hi']; if (arr?.length > 0) { console.log('array is not empty'); }

The optional chaining (?.) operator short-circuits if the reference is nullish (null or undefined).

In other words, if the arr variable stores a null or undefined value, the operator will return undefined instead of trying to access the length property on a null value and cause a runtime error.

App.js
const arr = null; if (arr?.length > 0) { console.log('array is not empty'); }

If you need to check if an array is empty, check if it's length property returns 0.

App.js
const arr = []; if (arr.length === 0) { console.log('array is empty'); }

If you're unsure whether the variable stores an array, you can check for the type of its value before accessing its length property.

index.js
let arr = ['hello']; if (Array.isArray(arr) && arr.length > 0) { // if this code block runs // 👉️ arr is not empty console.log('arr is not empty') }

We have 2 conditions in the if statement. We used the && (and) operator to signify that both conditions have to be satisfied for the if block to run.

We first check if the arr variable stores an array and then check if the array's length is greater than 0.

This approach is similar to the optional chaining one, but I prefer it because the optional chaining approach doesn't account for the case when arr is set to a string. Strings in JavaScript also have a length property.

Use the search field on my Home Page to filter through my more than 1,000 articles.