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

Table of Contents


You can check the value of the item if you only want to do so.

if (strValue) {
    //do something

If you have to verify that null is not an empty string, then I think you should check against "" , using the === operator.

if (strValue === "") {

I use the following to check if a string has null, empty, or undefined:

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

I use this method to check if a string has null, blank, or undefined.

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

You can check whether a string has white-space or is blank.

String.prototype.isEmpty = function() {
    return (this.length === 0 || !this.trim());

The answers to the above questions are excellent, but this one will be even better. Use dual NOT operators (!! Use dual NOT operators  (!!):

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

Or, you can use type casting

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

Both have the same function. Typecast the variable into Boolean.  str is a variable.

It returns  false for nullundefined0000,

It holds true  for strings  "0"  and whitespace " ".

How Lack of Rest Can Impact Your Finances Small Businesses Can Enhance File Management Following these Tips How Much Do Real Estate Agents Spend on Marketing? How to Engage Your Online Audience for Long-Lasting Success Why is Plagiarism Such a Big Deal? Resume Service Review: Why Everyone Should Use It