Check if an Array or a String is Empty in React

avatar
Borislav Hadzhiev

Last updated: Apr 7, 2024
4 min

banner

# Table of Contents

  1. Check if an Array is Empty in React
  2. Check if a String is Empty in React

If you need to check if a string is empty in React, click on the second subheading.

# 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 code for this article is available on GitHub

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

App.js
if (messages.length > 0) { console.log('array is NOT empty'); }

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

We set an onClick prop on the button element, so every time it's clicked a function is invoked.

App.js
<button onClick={() => setMessages(current => [...current, 'hello'])}> Add message </button>

The function adds an element to the state array each time the button is clicked.

Every time the state array changes, the useEffect hook is run.

App.js
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]);
The code for this article is available on GitHub

In our useEffect hook, we use the array's length to check if the array is empty or not.

If the length of the array is equal to 0, it's empty, otherwise, it contains at least 1 element.

# Check if an Array is Empty using optional chaining (?.)

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 code for this article is available on GitHub

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 its 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, check for the type of its value before accessing its length property.

index.js
let arr = ['bobbyhadz.com']; 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 met 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.

# Check if a String is Empty in React

To check if a string is empty in React, access its length property and check if it's equal to 0.

If the string's length is equal to 0, then the string is empty, otherwise it isn't empty.

App.js
import {useEffect, useState} from 'react'; export default function App() { const [message, setMessage] = useState(''); useEffect(() => { if (message.length === 0) { console.log('string is empty'); } else { console.log('string is NOT empty'); } // ๐Ÿ‘‡๏ธ trim leading and trailing whitespace if (message.trim().length === 0) { console.log('string is empty'); } else { console.log('string is NOT empty'); } }, [message]); return ( <div> <h2>String: {message}</h2> <button onClick={() => setMessage('Hello world')}> Set state </button> </div> ); }

check if string is empty

The code for this article is available on GitHub

The first if statement checks if the message variable stores an empty string.

App.js
if (message.length === 0) { console.log('string is empty'); } else { console.log('string is NOT empty'); }

We set the onClick prop on the button element, so every time the button is clicked, a function is invoked.

App.js
<button onClick={() => setMessage('Hello world')}> Set state </button>

On each click, we set the setMessage state variable to a string and the useEffect hook runs.

# Check if a String is empty in React using trim()

If you consider an empty string one that contains only spaces, you can use the trim() method to remove any leading or trailing whitespace before checking if the string is empty.

App.js
const str = ' '; if (str.trim().length === 0) { console.log('string is empty'); } else { console.log('string is NOT empty'); }
The code for this article is available on GitHub

The trim() method removes the leading and trailing spaces from a string. If the string contains only spaces, trim() returns an empty string.

App.js
// ๐Ÿ‘‡๏ธ "bobbyhadz.com" console.dir(' bobbyhadz.com ');

# Checking if a String is truthy in react

To check if a string is truthy and contains one or more characters, add the string to an if statement.

App.js
const str = 'bobbyhadz.com'; if (str) { // If this code block runs // ๐Ÿ‘‰๏ธ str is NOT "", undefined, null, 0, false, NaN console.log('string is truthy'); }

The code in the if block wouldn't run if the str variable is set to an empty string, undefined, null, 0, false or NaN.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev