Categories
is-empty javascript null

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

3649

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

7

  • 4

    just FYI, i think the most useful APIs for the String class are at Mozilla and javascript kit. [elated.com](elated.com/articles/working-with-strings ) has a tutorial on all of String’s properties, methods,… Please note: the Mozilla link has been updated to developer.mozilla.org/en/JavaScript/Reference/Global_Objects/…

    – Gene T

    Oct 2, 2008 at 15:16


  • Check this one : stackoverflow.com/a/36491147/7026966

    May 13, 2019 at 10:58

  • 1

    It would help greatly if the requirement was clearly specified. For what values should isEmpty return true? Checking for “” infers that it should only return true if the value is Type string and length 0. Many answers here assume it should also return true for some or all falsey values.

    – RobG

    Oct 16, 2019 at 12:47

  • str.length > -1

    Jan 31, 2021 at 4:29

  • I completely agree with @RobG, this question is badly defined. Why on earth would you consider null or undefined empty? An empty string is an empty string, it is not null or undefined

    – Flimm

    Aug 11, 2021 at 14:59

4482

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
}

13

  • 253

    Testing the length property may actually be faster than testing the string against “”, because the interpreter won’t have to create a String object from the string literal.

    Oct 1, 2008 at 20:07

  • 70

    @Vincent doing some naïve profiling in Chrome developer tools, testing === '' vs .length didn’t show any discernible improvement (and using .length only works if you can assume that you have a string)

    – bdukes

    Sep 27, 2010 at 13:19

  • 41

    @bdukes when you start to care about that kind of micro-optimizations, I don’t think Chrome is the browser where you are having most of your performance problems…

    Sep 27, 2010 at 16:18

  • 34

    Just to note, if your definition of “empty string” includes whitespace, then this solution is not appropriate. A string of 1 or more spaces returns true above. If you are using JQuery you can simply use this: if ($.trim(ref).length === 0) – as per this answer to a similar question: stackoverflow.com/questions/2031085/…

    Oct 3, 2011 at 15:02


  • 141

    As expected .length > 0 is actually much faster than comparing to a string literal! Check out this jsPerf

    – Chad

    Nov 28, 2011 at 21:54


1372

For checking if a variable is falsey or if it has length attribute equal to zero (which for a string, means it is empty), I use:

function isEmpty(str) {
    return (!str || str.length === 0 );
}

(Note that strings aren’t the only variables with a length attribute, arrays have them as well, for example.)

Alternativaly, you can use the (not so) newly optional chaining and arrow functions to simplify:

const isEmpty = (str) => (!str?.length);

It will check the length, returning undefined in case of a nullish value, without throwing an error. In the case of an empty value, zero is falsy and the result is still valid.

For checking if a variable is falsey or if the string only contains whitespace or is empty, I use:

function isBlank(str) {
    return (!str || /^\s*$/.test(str));
}

If you want, you can monkey-patch the String prototype like this:

String.prototype.isEmpty = function() {
    // This doesn't work the same way as the isEmpty function used 
    // in the first example, it will return true for strings containing only whitespace
    return (this.length === 0 || !this.trim());
};
console.log("example".isEmpty());

Note that monkey-patching built-in types are controversial, as it can break code that depends on the existing structure of built-in types, for whatever reason.

12

  • 47

    why 0 === str.length instead of str.length === 0 ?

    – Vincent

    Sep 23, 2013 at 8:11


  • 123

    @Vincent Conditions are often written like this if (variable == constant value) and if you forget an ‘=’ then you’re assigning the constant value to the variable instead of testing. The code will still work as you can assign variable in a if. So a safer way to write this condition is to reverse the constant value and the variable. This way when you test your code you’ll see an error (Invalid lef-hand side in assignment). You can also use something like JSHint to disallow assignment in conditions and be warned when you write one.

    Sep 23, 2013 at 9:58

  • 11

    /^\s*$/.test(str) can be replaced with str.trim().length === 0

    Jun 19, 2015 at 12:35

  • 47

    @Vincent this is also called “Yoda Conditions”, like if blue is the sky. See dodgycoder.net/2011/11/yoda-conditions-pokemon-exception.html

    – AZ.

    Jan 26, 2016 at 0:12

  • 3

    It isn’t really a good idea to be extending native prototypes though, it is generally considered a bad practice that a lot of people just recommend against doing so entirely as there are safer ways that are just as good. There is a SO discussion on the topic here, but every JS programming book I’ve read has strongly recommended against it. For OPs problem I usually just do if (!str) { // i am sure str is empty null or undefined here if I'm sure it won't be another data type }

    Jan 8, 2020 at 18:55


525

All the previous answers are good, but this will be even better. Use dual NOT operators (!!):

if (!!str) {
    // Some code here
}

Or use type casting:

if (Boolean(str)) {
    // Code here
}

Both do the same function. Typecast the variable to Boolean, where str is a variable.

  • It returns false for null, undefined, 0, 000, "", false.

  • It returns true for all string values other than the empty string (including strings like "0" and " ")

14

  • 52

    Is there any difference between the behavior of if(str) and if(!!str)?

    Dec 19, 2014 at 18:28

  • 7

    @PeterOlson if you are trying to save a variable as a boolean that checks multiple strings for content then you would want to do this.. aka var any = (!!str1 && !!str2 && !!str3) handling if there is a number in there as well

    Mar 10, 2015 at 23:00


  • 46

    This is the solution I always use. !!str.trim() to make sure the string is not made of whitespaces only.

    Feb 11, 2016 at 10:56


  • 23

    Not not looks like a hack, Boolean(str) is a lot more readable and less “wtfish”.

    – shinzou

    Oct 17, 2016 at 21:28

  • 11

    This is simply useless in a if, it converts falsy values to false and truthy values to true. A if block either executes or not based on wether the expression is truthy, there is no point adding !!

    – Oli Crt

    Sep 8, 2020 at 9:03