Is there a standard function to check for null, undefined, or blank variables in JavaScript?

Is there a universal JavaScript function that checks that a variable has a value and ensures that it’s not undefined or null? I’ve got this code, but I’m not sure if it covers all cases:

function isEmpty(val){ return (val === undefined || val == null || val.length <= 0) ? true : false; }

From my experience working with JavaScript, I’ve found that a lot of folks want a clean way to do a javascript check null or undefined along with handling blank values. Your function is almost there! One neat trick is to use val == null because it covers both null and undefined in one go, which simplifies things nicely. Here’s a streamlined version I use often:

function isEmpty(val) {
    return val == null || val.length === 0 || (typeof val === 'string' && !val.trim());
}

This function checks:

  • If val is null or undefined (val == null)
  • If it’s an empty string or string with only whitespace (!val.trim())
  • If it’s an empty array or anything with a length property (val.length === 0)

This handles most common edge cases efficiently when doing a javascript check null or undefined.

Building on that, I totally agree with @ishrth_fathima about using val == null for the javascript check null or undefined. In addition, trimming strings is key to catching those sneaky cases where the string might look empty but actually has spaces. One thing to keep in mind is the order of checks to avoid errors with types that don’t have a .length property. Here’s a slightly tweaked version I find even safer:

function isEmpty(val) {
    return val == null || (typeof val === 'string' && !val.trim()) || (Array.isArray(val) && val.length === 0);
}

By explicitly checking if val is an array before checking .length, you reduce unexpected errors. This way, your javascript check null or undefined and blank cases handle strings with spaces, arrays, and those nullish values gracefully."

Picking up from @ishrth_fathima and @emma-crepeau , I’ve found that the javascript check null or undefined often needs to handle not just arrays and strings, but sometimes objects too. Although objects don’t have a length, sometimes you want to consider them ‘empty’ if they have no keys. If that fits your use case, you might extend the function like this:

function isEmpty(val) {
    if (val == null) return true; // null or undefined
    if (typeof val === 'string' && !val.trim()) return true; // empty or whitespace string
    if (Array.isArray(val) && val.length === 0) return true; // empty array
    if (typeof val === 'object' && !Array.isArray(val)) {
        return Object.keys(val).length === 0; // empty object
    }
    return false;
}

This version takes your javascript check null or undefined a step further by covering empty objects as well — which can be quite handy depending on your needs. It’s a bit more verbose but covers a wider range of ‘empty’ cases naturally."