How to check if JavaScript Variable isEmpty
const isEmptyObject = (obj) => {
for(let key in obj) {
if(obj.hasOwnProperty(key)){
return false;
}
}
return true;
};
/**
* Check is empty.
*
* ... usage ...
* isNullOrEmpty( '' ); // true
* isNullOrEmpty( {} ); // true
* isNullOrEmpty( [] ); // true
* isNullOrEmpty( null ); // true
* isNullOrEmpty( undefined ); // true
*
* isNullOrEmpty( 'text' ); // false
* isNullOrEmpty( dom_element ); // false
* isNullOrEmpty( object ); // false
* isNullOrEmpty( [0] ); // false
* isNullOrEmpty( [ 'volume' : .5 ] ); // false
*
* @param obj
* @returns {boolean}
*/
const isEmpty = (obj) => {
// must test type of base object first
if (typeof obj == "undefined") {
return true;
}
// immediate
if ( obj == null || !obj ) {
return true;
}
// Array or associative array
if( Array.isArray(obj)){
if(!!Object.keys(obj).length){
return false;
}
if(!obj.length){
return true;
}
}
// Empty object or DOM element
if ( typeof obj == 'object' ){
if(isDomElement(obj)){
return false;
}
if(isEmptyObject(obj)){
return true
}
}
return false;
};
Written by david262929
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Objects javascript isempty isnullorempty
Authors
Related Tags
#objects javascript isempty isnullorempty
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#