Explain Codes LogoExplain Codes Logo

How do I check for an empty/undefined/null string in JavaScript?

javascript
prompt-engineering
functions
best-practices
Alex KataevbyAlex Kataev·Sep 17, 2024
TLDR

To readily detect if a string is empty, undefined, or null use: if (!str) {...}. To categorize space-filled strings as empty ones, apply: if (!str || !str.trim()) {...}.

Example:

// (Not so) top secret string let str; if (!str || !str.trim()) { // Why so empty? console.log('Empty-like string'); } else { console.log('Non-empty string'); }

The above makes use of truthiness in JavaScript, where undefined, null and empty strings are falsy. Implementing .trim() corners strings constituted only of spaces.

Null, Who's There?

To dodge confusion over whitespaces or different types, put into play:

  • Strict equality (=== or !==) for precise type juxtaposition.
  • Boolean function or logical NOT (!!) for open type conversion.
  • Regular Expressions to sift through whitespace.

Example:

// We could have been something, but you're just space let str = " "; if (str !== null && str !== undefined && str.trim() !== "") { console.log('Non-empty string'); } else { // We're on a break! console.log('Empty-like string'); }

The use of str.trim() ascertains that strings teeming with whitespace only do not pass as non-empty. Be aware that "0" and " " are truthy in JavaScript.

Checking the Unchecked

In some cases, simple conditionals may not suffice, and a utility function could come to the rescue:

// Preventing empty string crisis since 2022 function isBlank(str) { return (!str || /^\s*$/.test(str)); } if (isBlank(str)) { // This string is emptier than my refrigerator console.log('Empty-like or whitespace-only string'); } else { console.log('Non-empty string'); }

The isBlank function gauges for an actual empty value as well as a string loaded only with whitespace. Spares the refrigerator shame!

Avoiding the Undefined

To make certain the variable is defined before scrutinizing its content, marshal in optional chaining:

// This line alone, stops half of the universe's bugs if (!str?.length) { console.log('String is undefined, null, or empty'); }

Save yourself from ReferenceError, especially when wrangling with likely uninitialized variables.

Extra Gears for your Coding Vehicle

Driving through Data Types

In JavaScript, comprehend that "0" or false qualify as truthy when transfigured to strings:

if (Boolean(str)) { console.log('Non-empty string, even if "0" or "false"'); }

The right method for conversion and appraisal like Boolean(str) vs !!str can offer clear road signs in your code.

Spotting the string.Empty Pothole

Although JavaScript lacks a direct counterpart of other languages' string.Empty:

if (str === '') { console.log('Explicitly empty string'); }

This draws a clear line against the empty string literal.

Road-worthy String Content

To catch strings constituted of non-space characters, deploy a regular expression to replace all whitespace and then compare:

if (str.replace(/\s/g,"") === '') { console.log('String has no non-space characters'); }

This guarantees the inspection of content value rather than mere presence of characters.