How do I check for an empty/undefined/null string in JavaScript?
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:
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:
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:
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:
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:
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
:
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:
This guarantees the inspection of content value rather than mere presence of characters.
Was this article helpful?