2602
votes

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;
}
30
Protip, never do (truthy statement) ? true : false;. Just do (truthy statement);.David Baucum
@GeorgeJempty not a dup, since the other answer asks about strings in particular, whereas this one asks about variables.Madbreaks
Any correct answer to this question relies entirely on how you define "blank".Madbreaks
@Jay It doesn't hurt anything as far as execution of your code. It's just overly verbose. You wouldn't say, "Is are you hungry is true?" You just "Are you hungry" So in code just say if (hungry) … instead of if (hungry === true) …. Like all coding things in this manner, it's just a matter of taste. More specific to the example provided by the OP he's saying even more verbosely, "If it's true, then true, if not then false" But if it's true, then it's already true. And, if it's false, it's already false. This is akin to saying "If you're hungry then you are, and if not then you aren't."David Baucum

30 Answers

5003
votes

You can just check if the variable has a truthy value or not. That means

if( value ) {
}

will evaluate to true if value is not:

  • null
  • undefined
  • NaN
  • empty string ("")
  • 0
  • false

The above list represents all possible falsy values in ECMA-/Javascript. Find it in the specification at the ToBoolean section.

Furthermore, if you do not know whether a variable exists (that means, if it was declared) you should check with the typeof operator. For instance

if( typeof foo !== 'undefined' ) {
    // foo could get resolved and it's defined
}

If you can be sure that a variable is declared at least, you should directly check if it has a truthy value like shown above.

266
votes

The verbose method to check if value is undefined or null is:

return value === undefined || value === null;

You can also use the == operator but this expects one to know all the rules:

return value == null; // also returns true if value is undefined
103
votes
function isEmpty(value){
  return (value == null || value.length === 0);
}

This will return true for

undefined  // Because undefined == null

null

[]

""

and zero argument functions since a function's length is the number of declared parameters it takes.

To disallow the latter category, you might want to just check for blank strings

function isEmpty(value){
  return (value == null || value === '');
}
59
votes

This is the safest check and I haven't seen it posted here exactly like that:

if (typeof value !== 'undefined' && value) {
    //deal with value'
};

It will cover cases where value was never defined, and also any of these:

  • null
  • undefined (value of undefined is not the same as a parameter that was never defined)
  • 0
  • "" (empty string)
  • false
  • NaN

Edited: Changed to strict equality (!==) because it's the norm by now ;)

30
votes

You may find the following function useful:

function typeOf(obj) {
  return {}.toString.call(obj).split(' ')[1].slice(0, -1).toLowerCase();
}

Or in ES7 (comment if further improvements)

function typeOf(obj) {
  const { toString } = Object.prototype;
  const stringified = obj::toString();
  const type = stringified.split(' ')[1].slice(0, -1);

  return type.toLowerCase();
}

Results:

typeOf(); //undefined
typeOf(null); //null
typeOf(NaN); //number
typeOf(5); //number
typeOf({}); //object
typeOf([]); //array
typeOf(''); //string
typeOf(function () {}); //function
typeOf(/a/) //regexp
typeOf(new Date()) //date
typeOf(new WeakMap()) //weakmap
typeOf(new Map()) //map

"Note that the bind operator (::) is not part of ES2016 (ES7) nor any later edition of the ECMAScript standard at all. It's currently a stage 0 (strawman) proposal for being introduced to the language." – Simon Kjellberg. the author wishes to add his support for this beautiful proposal to receive royal ascension.

27
votes

The first answer with best rating is wrong. If value is undefined it will throw an exception in modern browsers. You have to use:

if (typeof(value) !== "undefined" && value)

or

if (typeof value  !== "undefined" && value)
22
votes

A solution I like a lot:

Let's define that a blank variable is null, or undefined, or if it has length, it is zero, or if it is an object, it has no keys:

function isEmpty (value) {
  return (
    // null or undefined
    (value == null) ||

    // has length and it's zero
    (value.hasOwnProperty('length') && value.length === 0) ||

    // is an Object and has no keys
    (value.constructor === Object && Object.keys(value).length === 0)
  )
}

Returns:

  • true: undefined, null, "", [], {}
  • false: true, false, 1, 0, -1, "foo", [1, 2, 3], { foo: 1 }
21
votes

This condition check

if (!!foo) {
    //foo is defined
}

is all you need.

19
votes

! check for empty strings (""), null, undefined, false and the number 0 and NaN. Say, if a string is empty var name = "" then console.log(!name) returns true.

function isEmpty(val){
  return !val;
}

this function will return true if val is empty, null, undefined, false, the number 0 or NaN.

OR

According to your problem domain you can just use like !val or !!val.

18
votes

You are a bit overdoing it. To check if a variable is not given a value, you would only need to check against undefined and null.

function isEmpty(value){
    return (typeof value === "undefined" || value === null);
}

This is assuming 0, "", and objects(even empty object and array) are valid "values".

16
votes

Take a look at the new ECMAScript Nullish coalescing operator

You can think of this feature - the ?? operator - as a way to “fall back” to a default value when dealing with null or undefined.

let x = foo ?? bar();

Again, the above code is equivalent to the following.

let x = (foo !== null && foo !== undefined) ? foo : bar();
11
votes

Here's mine - returns true if value is null, undefined, etc or blank (ie contains only blank spaces):

function stringIsEmpty(value) {

    return value ? value.trim().length == 0 : true;

}
10
votes

If you prefer plain javascript try this:

  /**
   * Checks if `value` is empty. Arrays, strings, or `arguments` objects with a
   * length of `0` and objects with no own enumerable properties are considered
   * "empty".
   *
   * @static
   * @memberOf _
   * @category Objects
   * @param {Array|Object|string} value The value to inspect.
   * @returns {boolean} Returns `true` if the `value` is empty, else `false`.
   * @example
   *
   * _.isEmpty([1, 2, 3]);
   * // => false
   *
   * _.isEmpty([]);
   * // => true
   *
   * _.isEmpty({});
   * // => true
   *
   * _.isEmpty('');
   * // => true
   */

function isEmpty(value) {
    if (!value) {
      return true;
    }
    if (isArray(value) || isString(value)) {
      return !value.length;
    }
    for (var key in value) {
      if (hasOwnProperty.call(value, key)) {
        return false;
      }
    }
    return true;
  }

Otherwise, if you are already using underscore or lodash, try:

_.isEmpty(value)
7
votes
return val || 'Handle empty variable'

is a really nice and clean way to handle it in a lot of places, can also be used to assign variables

const res = val || 'default value'
6
votes

If the variable hasn't been declared, you wont be able to test for undefined using a function because you will get an error.

if (foo) {}
function (bar) {}(foo)

Both will generate an error if foo has not been declared.

If you want to test if a variable has been declared you can use

typeof foo != "undefined"

if you want to test if foo has been declared and it has a value you can use

if (typeof foo != "undefined" && foo) {
    //code here
}
6
votes

Vacuousness


Truthiness/Falsiness


Null vs Undefined

  • Trying to access a non-existent property gives undefined
  • Omitting a parameter when calling a function results in that parameter receiving undefined:

let f = a => a;
console.log(f('hi'));
console.log(f());
  • Parameters with default values receive the default only when given undefined, not null:

let f = (v='hello') => v;
console.log(f(null));
console.log(f(undefined));

Non-generic Vacuousness

let isType = (value, Cls) => {
  // Intentional use of loose comparison operator detects `null`
  // and `undefined`, and nothing else!
  return value != null && Object.getPrototypeOf(value).constructor === Cls;
};

Note that this function ignores polymorphism - it expects value to be a direct instance of Cls, and not an instance of a subclass of Cls. I avoid instanceof for two main reasons:

  • ([] instanceof Object) === true ("An Array is an Object")
  • ('' instanceof String) === false ("A String is not a String")

Note that Object.getPrototypeOf is used to avoid a case like let v = { constructor: String }; The isType function still returns correctly for isType(v, String) (false), and isType(v, Object) (true).

Overall, I recommend using this isType function along with these tips:

  • Minimize the amount of code processing values of unknown type. E.g., for let v = JSON.parse(someRawValue);, our v variable is now of unknown type. As early as possible, we should limit our possibilities. The best way to do this can be by requiring a particular type: e.g. if (!isType(v, Array)) throw new Error('Expected Array'); - this is a really quick and expressive way to remove the generic nature of v, and ensure it's always an Array. Sometimes, though, we need to allow v to be of multiple types. In those cases, we should create blocks of code where v is no longer generic, as early as possible:

if (isType(v, String)) {
  /* v isn't generic in this block - It's a String! */
} else if (isType(v, Number)) {
  /* v isn't generic in this block - It's a Number! */
} else if (isType(v, Array)) {
  /* v isn't generic in this block - it's an Array! */
} else {
  throw new Error('Expected String, Number, or Array');
}
  • Always use "whitelists" for validation. If you require a value to be, e.g., a String, Number, or Array, check for those 3 "white" possibilities, and throw an Error if none of the 3 are satisfied. We should be able to see that checking for "black" possibilities isn't very useful: Say we write if (v === null) throw new Error('Null value rejected'); - this is great for ensuring that null values don't make it through, but if a value does make it through, we still know hardly anything about it. A value v which passes this null-check is still VERY generic - it's anything but null! Blacklists hardly dispell generic-ness.
  • Unless a value is null, never consider "a vacuous value". Instead, consider "an X which is vacuous". Essentially, never consider doing anything like if (isEmpty(val)) { /* ... */ } - no matter how that isEmpty function is implemented (I don't want to know...), it isn't meaningful! And it's way too generic! Vacuousness should only be calculated with knowledge of val's type. Vacuousness-checks should look like this:
    • "A string, with no chars": if (isType(val, String) && val.length === 0) ...

    • "An Object, with 0 props": if (isType(val, Object) && Object.entries(val).length === 0) ...

    • "A number, equal or less than zero": if (isType(val, Number) && val <= 0) ...

    • "An Array, with no items": if (isType(val, Array) && val.length === 0) ...

    • The only exception is when null is used to signify certain functionality. In this case it's meaningful to say: "A vacuous value": if (val === null) ...

5
votes

To check Default Value

function typeOfVar (obj) {
      return {}.toString.call(obj).split(' ')[1].slice(0, -1).toLowerCase();
}
function isVariableHaveDefaltVal(variable) {
    if ( typeof(variable) === 'string' ) {  // number, boolean, string, object 
        console.log(' Any data Between single/double Quotes is treated as String ');        
        return (variable.trim().length === 0) ? true : false;
    }else if ( typeof(variable) === 'boolean' ) {
      console.log('boolean value with default value \'false\'');
        return (variable === false) ? true : false;
    }else if ( typeof(variable) === 'undefined' ) {
        console.log('EX: var a; variable is created, but has the default value of undefined.'); 
        return true;
    }else if ( typeof(variable) === 'number' ) { 
        console.log('number : '+variable);
        return (variable === 0 ) ? true : false;
    }else if ( typeof(variable) === 'object' ) {
   //   -----Object-----
        if (typeOfVar(variable) === 'array' && variable.length === 0) {
            console.log('\t Object Array with length = ' + [].length); // Object.keys(variable)
            return true;
        }else if (typeOfVar(variable) === 'string' && variable.length === 0 ) {
            console.log('\t Object String with length = ' + variable.length);
            return true;
        }else if (typeOfVar(variable) === 'boolean' ) {
            console.log('\t Object Boolean = ' + variable);
            return (variable === false) ? true : false;
        }else if (typeOfVar(variable) === 'number' ) {
            console.log('\t Object Number = ' + variable);
            return (variable === 0 ) ? true : false;
        }else if (typeOfVar(variable) === 'regexp' && variable.source.trim().length === 0 ) {
       console.log('\t Object Regular Expression : ');
        return true;
        }else if (variable === null) {
       console.log('\t Object null value');
        return true;
        }
    }
    return false;
}
var str = "A Basket For Every Occasion";
str = str.replace(/\s/g, "-");
//The "g" flag in the regex will cause all spaces to get replaced.

check Result:

isVariableHaveDefaltVal(' '); // string          
isVariableHaveDefaltVal(false); // boolean       
var a;           
isVariableHaveDefaltVal(a);               
isVariableHaveDefaltVal(0); // number             
isVariableHaveDefaltVal(parseInt('')); // NAN isNAN(' '); - true         
isVariableHaveDefaltVal(null);              
isVariableHaveDefaltVal([]);               
isVariableHaveDefaltVal(/ /);              
isVariableHaveDefaltVal(new Object(''));               
isVariableHaveDefaltVal(new Object(false));            
isVariableHaveDefaltVal(new Object(0)); 
typeOfVar( function() {} );

I used @Vix function() to check the object of which type.

using instansof «

var prototypes_or_Literals = function (obj) {
    switch (typeof(obj)) {
        // object prototypes
        case 'object':
            if (obj instanceof Array)
                return '[object Array]';
            else if (obj instanceof Date)
                return '[object Date]';
            else if (obj instanceof RegExp)
                return '[object regexp]';
            else if (obj instanceof String)
                return '[object String]';
            else if (obj instanceof Number)
                return '[object Number]';

            else
                return 'object';
        // object literals
        default:
            return typeof(obj);
    }   
};
output test «
prototypes_or_Literals( '' ) // "string"
prototypes_or_Literals( new String('') ) // "[object String]"
Object.prototype.toString.call("foo bar") //"[object String]"        
5
votes
function isEmpty(obj) {
    if (typeof obj == 'number') return false;
    else if (typeof obj == 'string') return obj.length == 0;
    else if (Array.isArray(obj)) return obj.length == 0;
    else if (typeof obj == 'object') return obj == null || Object.keys(obj).length == 0;
    else if (typeof obj == 'boolean') return false;
    else return !obj;
}

In ES6 with trim to handle whitespace strings:

const isEmpty = value => {
    if (typeof value === 'number') return false
    else if (typeof value === 'string') return value.trim().length === 0
    else if (Array.isArray(value)) return value.length === 0
    else if (typeof value === 'object') return value == null || Object.keys(value).length === 0
    else if (typeof value === 'boolean') return false
    else return !value
}
5
votes

It may be usefull.

All values in array represent what you want to be (null, undefined or another things) and you search what you want in it.

var variablesWhatILookFor = [null, undefined, ''];
variablesWhatILookFor.indexOf(document.DocumentNumberLabel) > -1
5
votes

The probably shortest answer is

val==null || val==''

if you change rigth side to val==='' then empty array will give false. Proof

function isEmpty(val){
    return val==null || val==''
}

// ------------
// TEST
// ------------

var log = (name,val) => console.log(`${name} -> ${isEmpty(val)}`);

log('null', null);
log('undefined', undefined);
log('NaN', NaN);
log('""', "");
log('{}', {});
log('[]', []);
log('[1]', [1]);
log('[0]', [0]);
log('[[]]', [[]]);
log('true', true);
log('false', false);
log('"true"', "true");
log('"false"', "false");
log('Infinity', Infinity);
log('-Infinity', -Infinity);
log('1', 1);
log('0', 0);
log('-1', -1);
log('"1"', "1");
log('"0"', "0");
log('"-1"', "-1");

// "void 0" case
console.log('---\n"true" is:', true);
console.log('"void 0" is:', void 0);
log(void 0,void 0); // "void 0" is "undefined" - so we should get here TRUE

More details about == (source here)

Enter image description here

BONUS: Reason why === is more clear than ==

Enter image description here

To write clear and easy understandable code, use explicite list of accepted values

val===undefined || val===null || val===''|| (Array.isArray(val) && val.length===0)

function isEmpty(val){
    return val===undefined || val===null || val==='' || (Array.isArray(val) && val.length===0)
}

// ------------
// TEST
// ------------

var log = (name,val) => console.log(`${name} -> ${isEmpty(val)}`);

log('null', null);
log('undefined', undefined);
log('NaN', NaN);
log('""', "");
log('{}', {});
log('[]', []);
log('[1]', [1]);
log('[0]', [0]);
log('[[]]', [[]]);
log('true', true);
log('false', false);
log('"true"', "true");
log('"false"', "false");
log('Infinity', Infinity);
log('-Infinity', -Infinity);
log('1', 1);
log('0', 0);
log('-1', -1);
log('"1"', "1");
log('"0"', "0");
log('"-1"', "-1");

// "void 0" case
console.log('---\n"true" is:', true);
console.log('"void 0" is:', void 0);
log(void 0,void 0); // "void 0" is "undefined" - so we should get here TRUE
4
votes

If you are using TypeScript and don't want to account for "values those are false" then this is the solution for you:

First: import { isNullOrUndefined } from 'util';

Then: isNullOrUndefined(this.yourVariableName)

Please Note: As mentioned below this is now deprecated, use value === undefined || value === null instead. ref.

4
votes

Try With Different Logic. You can use bellow code for check all four(4) condition for validation like not null, not blank, not undefined and not zero only use this code (!(!(variable))) in javascript and jquery.

function myFunction() {
    var data;  //The Values can be like as null, blank, undefined, zero you can test

    if(!(!(data)))
    {
        alert("data "+data);
    } 
    else 
    {
        alert("data is "+data);
    }
}
2
votes
function isEmpty(val){
    return !val;
}

but this solution is over-engineered, if you dont'want to modify the function later for busines-model needings, then is cleaner to use it directly in code:

if(!val)...
2
votes
var myNewValue = myObject && myObject.child && myObject.child.myValue;

This will never throw an error. If myObject, child, or myValue is null then myNewValue will be null. No errors will be thrown

2
votes

For everyone coming here for having similar question, the following works great and I have it in my library the last years:

(function(g3, $, window, document, undefined){
   g3.utils = g3.utils || {};
/********************************Function type()********************************
* Returns a lowercase string representation of an object's constructor.
* @module {g3.utils}
* @function {g3.utils.type}
* @public
* @param {Type} 'obj' is any type native, host or custom.
* @return {String} Returns a lowercase string representing the object's 
* constructor which is different from word 'object' if they are not custom.
* @reference http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/
* http://stackoverflow.com/questions/3215046/differentiating-between-arrays-and-hashes-in-javascript
* http://javascript.info/tutorial/type-detection
*******************************************************************************/
g3.utils.type = function (obj){
   if(obj === null)
      return 'null';
   else if(typeof obj === 'undefined')
      return 'undefined';
   return Object.prototype.toString.call(obj).match(/^\[object\s(.*)\]$/)[1].toLowerCase();
};
}(window.g3 = window.g3 || {}, jQuery, window, document));
2
votes

If you want to avoid getting true if the value is any of the following, according to jAndy's answer:

  • null
  • undefined
  • NaN
  • empty string ("")
  • 0
  • false

One possible solution that might avoid getting truthy values is the following:

function isUsable(valueToCheck) {
    if (valueToCheck === 0     || // Avoid returning false if the value is 0.
        valueToCheck === ''    || // Avoid returning false if the value is an empty string.
        valueToCheck === false || // Avoid returning false if the value is false.
        valueToCheck)             // Returns true if it isn't null, undefined, or NaN.
    {
        return true;
    } else {
        return false;
    }
}

It would be used as follows:

if (isUsable(x)) {
    // It is usable!
}
// Make sure to avoid placing the logical NOT operator before the parameter (isUsable(!x)) and instead, use it before the function, to check the returned value.
if (!isUsable(x)) {
    // It is NOT usable!
}

In addition to those scenarios, you may want to return false if the object or array is empty:

You would go about it this way:

function isEmptyObject(valueToCheck) {
    if(typeof valueToCheck === 'object' && !Object.keys(valueToCheck).length){
        // Object is empty!
        return true;
    } else {
        // Object is not empty!
        return false;
    }
}

function isEmptyArray(valueToCheck) {
    if(Array.isArray(valueToCheck) && !valueToCheck.length) {
        // Array is empty!
        return true;
    } else {
        // Array is not empty!
        return false;
    }
}

If you wish to check for all whitespace strings (" "), you may do the following:

function isAllWhitespace(){
    if (valueToCheck.match(/^ *$/) !== null) {
        // Is all whitespaces!
        return true;
    } else {
        // Is not all whitespaces!
        return false;
    }
}

Note: hasOwnProperty returns true for empty strings, 0, false, NaN, null, and undefined, if the variable was declared as any of them, so it might not be the best to use. The function may be modified to use it to show that it was declared, but is not usable.

2
votes

Code on GitHub

const isEmpty = value => (
  (!value && value !== 0 && value !== false)
  || (Array.isArray(value) && value.length === 0)
  || (isObject(value) && Object.keys(value).length === 0)
  || (typeof value.size === 'number' && value.size === 0)

  // `WeekMap.length` is supposed to exist!?
  || (typeof value.length === 'number'
      && typeof value !== 'function' && value.length === 0)
);

// Source: https://levelup.gitconnected.com/javascript-check-if-a-variable-is-an-object-and-nothing-else-not-an-array-a-set-etc-a3987ea08fd7
const isObject = value =>
  Object.prototype.toString.call(value) === '[object Object]';

Poor man's tests 😁

const test = () => {
  const run = (label, values, expected) => {
    const length = values.length;
    console.group(`${label} (${length} tests)`);
    values.map((v, i) => {
      console.assert(isEmpty(v) === expected, `${i}: ${v}`);
    });
    console.groupEnd();
  };

  const empty = [
    null, undefined, NaN, '', {}, [],
    new Set(), new Set([]), new Map(), new Map([]),
  ];
  const notEmpty = [
    ' ', 'a', 0, 1, -1, false, true, {a: 1}, [0],
    new Set([0]), new Map([['a', 1]]),
    new WeakMap().set({}, 1),
    new Date(), /a/, new RegExp(), () => {},
  ];
  const shouldBeEmpty = [
    {undefined: undefined}, new Map([[]]),
  ];

  run('EMPTY', empty, true);
  run('NOT EMPTY', notEmpty, false);
  run('SHOULD BE EMPTY', shouldBeEmpty, true);
};

Test results:

EMPTY (10 tests)
NOT EMPTY (16 tests)
SHOULD BE EMPTY (2 tests)
  Assertion failed: 0: [object Object]
  Assertion failed: 1: [object Map]
2
votes

The optional chaining operator provides a way to simplify accessing values through connected objects when it's possible that a reference or function may be undefined or null.

let customer = {
  name: "Carl",
  details: {
    age: 82,
    location: "Paradise Falls" // detailed address is unknown
  }
};
let customerCity = customer.details?.address?.city;

The nullish coalescing operator may be used after optional chaining in order to build a default value when none was found:

let customer = {
  name: "Carl",
  details: { age: 82 }
};
const customerCity = customer?.city ?? "Unknown city";
console.log(customerCity); // Unknown city
2
votes
function notEmpty(value){
  return (typeof value !== 'undefined' && value.trim().length);
}

it will also check white spaces (' ') along with following:

  • null ,undefined ,NaN ,empty ,string ("") ,0 ,false
2
votes

You could use the nullish coalescing operator ?? to check for null and undefined values. See the MDN Docs

null ?? 'default string'; // returns "default string"

0 ?? 42;  // returns 0

(null || undefined) ?? "foo"; // returns "foo"