2
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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

case 'string' is actually useless, empty strings are falsy :)
Edge case if it is a number notEmpty(0) (which was not in the orginal)
yeah, that was not in the original method and since he is returning false for false boolean value, it probably means he wants false for 0 as well, I'm not sure.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.