HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptCritical

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
emptyhowcheckforundefinedstringjavascriptnull

Problem

Is there a string.Empty in JavaScript, or is it just a case of checking for ""?

Solution

Empty string, undefined, null, ...

To check for a truthy value:

if (strValue) {
    // strValue was non-empty string, true, 42, Infinity, [], ...
}


To check for a falsy value:

if (!strValue) {
    // strValue was empty string, false, 0, null, undefined, ...
}


Empty string (only!)

To check for exactly an empty string, compare for strict equality against "" using the === operator:

if (strValue === "") {
    // strValue was empty string
}


To check for not an empty string strictly, use the !== operator:

if (strValue !== "") {
    // strValue was not an empty string
}

Code Snippets

if (strValue) {
    // strValue was non-empty string, true, 42, Infinity, [], ...
}
if (!strValue) {
    // strValue was empty string, false, 0, null, undefined, ...
}
if (strValue === "") {
    // strValue was empty string
}
if (strValue !== "") {
    // strValue was not an empty string
}

Context

Stack Overflow Q#154059, score: 5116

Revisions (0)

No revisions yet.