Forum Discussion

BenoitB's avatar
BenoitB
Community Hero
4 years ago

[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);
}

 

 

 

3 Replies

  • BenoitB's avatar
    BenoitB
    Community Hero

    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)));
    }
      • BenoitB's avatar
        BenoitB
        Community Hero

        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 😉