Skip to content

Instantly share code, notes, and snippets.

@marcocesarato
Last active April 14, 2021 07:40
Show Gist options
  • Save marcocesarato/8e5db06b1ae997b9138136fc497376ba to your computer and use it in GitHub Desktop.
Save marcocesarato/8e5db06b1ae997b9138136fc497376ba to your computer and use it in GitHub Desktop.
Check if variable is empty on javascript
/**
* Is empty
* @param x
* @returns {boolean}
*/
export const isEmpty = (x) => {
// Generic
if (typeof x !== "boolean" && !x) {
return true;
}
// Strings
if (typeof x === "string") {
x = x.replace(/^\s+|\s+$|\s+(?=\s)/g, "");
return x === "";
}
// Nulls and undefined
if (x == null) {
return true;
}
// Arrays
if (Array.isArray(x) && x.length === 0) {
return true;
}
// Functions
if (Object.prototype.toString.call(x).indexOf("Function") > -1) {
let m = x.toString().match(/{([\s\S]*)}/m)[1];
let body = m.replace(/^\s*\/\/.*$/gm, "");
return isEmpty(body);
}
// Objects
if (typeof x === "object") {
if (Object.keys(x).length === 0) {
return true;
}
for (let key in x) {
if (x.hasOwnProperty(key) && !isEmpty(x[key])) {
return false;
}
}
return true;
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment