Skip to content

Instantly share code, notes, and snippets.

@olaferlandsen
Last active January 24, 2020 16:48
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save olaferlandsen/87738217283363769eb60739420becaf to your computer and use it in GitHub Desktop.
Save olaferlandsen/87738217283363769eb60739420becaf to your computer and use it in GitHub Desktop.
isEmpty is a compilation of functions to check if is a empty value on javascript compatible with ECMA5+
/**
*
* boolean isEmpty ( value )
*
* Example:
*
* var a = null;
* if (isEmpty(a)) {
* alert ('empty variable');
* }
*/
function isEmpty (value) {
if (value == null || value == undefined) {
return true;
}
if (value.prop && value.prop.constructor === Array) {
return value.length == 0;
}
else if (typeof value == 'object') {
return Object.keys(value).length === 0 && value.constructor === Object
}
else if (typeof value == 'string') {
return value.length == 0;
}
else if (typeof value == 'number') {
return value == 0;
} else if (!value) {
return true;
}
return false;
}
/**
*
* Example:
*
* var a = "";
* if (a.isEmpty()) {
* alert ('empty string');
* }
*/
String.prototype.isEmpty = function() {
return this.toString().length == 0;
};
/**
*
* Example:
*
* var a = 1;
* if (a.isEmpty()) {
* alert ('empty number');
* }
*
* Note:
*
* Use only with variable.
*/
Number.prototype.isEmpty = function() {
return this === 0;
};
/**
*
* Example:
*
* var a = [];
* if (a.isEmpty()) {
* alert ('empty array');
* }
*/
Array.prototype.isEmpty = function() {
return this.length == 0;
};
/**
*
* Example:
*
* var a = {};
* if (a.isEmpty()) {
* alert ('empty object');
* }
*
* Note:
* Dont work with null value.
*/
Object.prototype.isEmpty = function() {
return Object.keys(this).length === 0 && this.constructor === Object;
};
@tesmen
Copy link

tesmen commented Mar 24, 2017

"Object.prototype.isEmpty" kills Object as hash abilities

@olaferlandsen
Copy link
Author

@tesmen can you give me an example or log 😄
thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment