Search code examples
javascripttypesisnull

Javascript Null and Empty check


export const notEmpty = (data) => {
  const type = Object.prototype.toString.call(data).slice(8, -1).toLowerCase();
  switch (type) {
    case 'null':
    case 'undefined':
      return false;
    case 'object':
      return Object.keys(data).length > 0;
    case 'array':
    case 'string':
      return data !== 'undefined' && data !== 'null' && data.length > 0;
    case 'boolean':
      return !!data;
    default:
      return true;
  }
};

I've made above function for checking null, undefined, '' and empty Array and Object. But as you can see, it has many ifs. Is there another better solution for checking them?


Solution

  • Your current function doesn't look bad, but you can improve it like this:

    const notEmpty = (data) => {
      if (!data) return false;
      
      if (typeof data === 'object') return Object.keys(data).length > 0;
    
      return true;
    };
    
    console.log(notEmpty(null));
    console.log(notEmpty(undefined));
    console.log(notEmpty(''));
    console.log(notEmpty({}));
    console.log(notEmpty([]));
    console.log(notEmpty(false));
    
    console.log(notEmpty({ a: 1 }));
    console.log(notEmpty(true));
    console.log(notEmpty('abc'));
    console.log(notEmpty([1, 2, 3]));

    Arrays are objects, so the above will check for arrays as well.