Check if Variable is Undefined in React

avatar

Borislav Hadzhiev

Last updated: Apr 25, 2022

banner

Photo from Unsplash

Check if Variable is Undefined in React #

To check for undefined in React, use a comparison to check if the value is equal or is not equal to undefined, e.g. if (myValue === undefined) {} or if (myValue !== undefined) {}. If the condition is met, the if block will run.

App.js
import {useEffect, useState} from 'react'; export default function App() { const [message, setMessage] = useState(undefined); useEffect(() => { // ✅ Check if NOT equal to undefined if (message !== undefined) { console.log('variable is NOT undefined'); } // ✅ Check if undefined if (message === undefined) { console.log('variable is undefined'); } // ✅ Check if value is NOT equal to undefined and null if (message !== undefined && message !== null) { console.log('variable is NOT undefined or null'); } // ✅ Check if value is equal to undefined or null if (message === undefined || message === null) { console.log('variable is undefined or null'); } }, [message]); return ( <div> <button onClick={() => setMessage('Hello world')}>Set message</button> <h2>{message}</h2> </div> ); }

If our first if statement, we check if the message variable is not equal to undefined.

The second example checks if the variable is equal to undefined.

The third if statement checks if the variable is not equal to undefined and not equal to null.

The fourth example checks if the variable is equal to undefined or equal to null.

We used the useEffect hook to track changes to the message state variable, however you can perform the check anywhere in your code.

You can also check if a variable stores a truthy value.

The truthy values are all values that are not falsy.

The falsy values in JavaScript are: undefined, null, false, 0, "" (empty string), NaN (not a number).

App.js
import {useEffect, useState} from 'react'; export default function App() { const [message, setMessage] = useState(undefined); useEffect(() => { if (message) { console.log('✅ variable is truthy'); } if (!message) { console.log('⛔️ variable is falsy'); } }, [message]); return ( <div> <button onClick={() => setMessage('Hello world')}>Set message</button> <h2>{message}</h2> </div> ); }

The first condition checks if the message variable stores a truthy value.

The variable could store any value other than the 7 falsy values for the condition to be met.

The second if statement checks if the variable stores one of the 7 falsy values - undefined, null, false, 0, "" (empty string), NaN (not a number).

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.