BenoitB
4 years agoCommunity Hero
[JS SCRIPT] Best way to determine if variable is empty
Hello all,
Currently i use these routines to determine if a variable or an object is "empty" (undefined, null, empty).
Works well but curious if you have better implementation on your side ?
Looking also a convenient way (better than recursive call) of adding multiple levels object empty detection, if you have a trick please share it !
// Return true if variable is undefined or empty
// Works only on object of one level
// For standard object variable (string, table, number, ..) use isEmptyVar()
function isEmptyObject(obj) {
return (typeof obj == 'undefined') || (Object.keys(obj).length === 0 && obj.constructor === Object);
}
// Return true if variable is undefined, null or empty
// For user object variable use isEmptyObject()
function isEmptyVar(variable) {
return ((typeof variable == 'undefined') || (variable == null) || ((typeof variable == 'string') && ((variable == '') || (variable == 'undefined'))) || ((typeof variable == 'object') && (variable.length == 0)));
}
// Return true if element is undefined, null or empty
function isEmpty(obj) {
if ((typeof obj == 'object') && (obj.constructor === Object))
return isEmptyObject(obj)
else
return isEmptyVar(obj);
}