[JS SCRIPT] Best way to determine if variable is empty
- Bookmark
- Subscribe
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
06-24-2020
02:26 AM
06-24-2020
02:26 AM
[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);
}
Un sourire et ça repart
Labels:
- Labels:
-
TechCorner
3 REPLIES 3
- Bookmark
- Subscribe
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
06-25-2020
12:20 AM
06-25-2020
12:20 AM
The one-in-all is :
/**
* Tester si une variable est vide
* @function
* @Param {Object} variable - Variable à évaluer, les objets complexes (plus d'un niveau) ne sont pas évalués correctement
* @returns {boolean} Renvoie <b>true</b> si la variable est null ou undefined ou "" ou tableau/objet simple vide
*/
function isEmpty(Variable) {
if ((typeof Variable == 'object') && (Variable.constructor === Object))
return Object.keys(Variable).length === 0
else
return ((typeof Variable == 'undefined') || (Variable == null) || ((typeof Variable == 'string') && ((Variable == '') || (Variable == 'undefined'))) || ((typeof Variable == 'object') && (Variable.length == 0)));
}
Un sourire et ça repart
- Bookmark
- Subscribe
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
06-28-2020
11:28 PM
06-28-2020
11:28 PM
@BenoitB thanks a lot for sharing this!
Sonya Mihaljova
Community and Education Specialist
- Bookmark
- Subscribe
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
06-29-2020
02:29 AM
06-29-2020
02:29 AM
Txs @sonya_m but i'll appreciate if any other method are used by Smartbearians or if they have a trick for complex object empty detection 😉
Un sourire et ça repart
