[javascript] Checking something isEmpty in Javascript?

How can I check if a variable is empty in Javascript? Sorry for the stupid question, but I'm a newbie in Javascript!

if(response.photo) is empty {
    do something
else {
    do something else
}

response.photo was from JSON, and it could be empty sometimes, empty data cells! I want to check if it's empty.

This question is related to javascript jquery

The answer is


just put the variable inside the if condition, if variable has any value it will return true else false.

if (response.photo){ // if you are checking for string use this if(response.photo == "") condition
 alert("Has Value");
}
else
{
 alert("No Value");
};

if (myVar == undefined)

will work to see if the var is declared but not initalized.


What about doing like this.

JSON.stringify({}) === "{}"


what am I missing if empty array... keyless object... falseness const isEmpty = o => Array.isArray(o) && !o.join('').length || typeof o === 'object' && !Object.keys(o).length || !(+value);


Here my simplest solution.

Inspired by PHP empty function

_x000D_
_x000D_
function empty(n){_x000D_
 return !(!!n ? typeof n === 'object' ? Array.isArray(n) ? !!n.length : !!Object.keys(n).length : true : false);_x000D_
}_x000D_
_x000D_
//with number_x000D_
console.log(empty(0));        //true_x000D_
console.log(empty(10));       //false_x000D_
_x000D_
//with object_x000D_
console.log(empty({}));       //true_x000D_
console.log(empty({a:'a'}));  //false_x000D_
_x000D_
//with array_x000D_
console.log(empty([]));       //true_x000D_
console.log(empty([1,2]));    //false_x000D_
_x000D_
//with string_x000D_
console.log(empty(''));       //true_x000D_
console.log(empty('a'));      //false
_x000D_
_x000D_
_x000D_


const isEmpty = val => val == null || !(Object.keys(val) || val).length;


This should cover all cases:

function empty( val ) {

    // test results
    //---------------
    // []        true, empty array
    // {}        true, empty object
    // null      true
    // undefined true
    // ""        true, empty string
    // ''        true, empty string
    // 0         false, number
    // true      false, boolean
    // false     false, boolean
    // Date      false
    // function  false

        if (val === undefined)
        return true;

    if (typeof (val) == 'function' || typeof (val) == 'number' || typeof (val) == 'boolean' || Object.prototype.toString.call(val) === '[object Date]')
        return false;

    if (val == null || val.length === 0)        // null or 0 length array
        return true;

    if (typeof (val) == "object") {
        // empty object

        var r = true;

        for (var f in val)
            r = false;

        return r;
    }

    return false;
}

This is a bigger question than you think. Variables can empty in a lot of ways. Kinda depends on what you need to know.

// quick and dirty will be true for '', null, undefined, 0, NaN and false.
if (!x) 

// test for null OR undefined
if (x == null)  

// test for undefined OR null 
if (x == undefined) 

// test for undefined
if (x === undefined) 
// or safer test for undefined since the variable undefined can be set causing tests against it to fail.
if (typeof x == 'undefined') 

// test for empty string
if (x === '') 

// if you know its an array
if (x.length == 0)  
// or
if (!x.length)

// BONUS test for empty object
var empty = true, fld;
for (fld in x) {
  empty = false;
  break;
}

Empty check on a JSON's key depends on use-case. For a common use-case, we can test for following:

  1. Not null
  2. Not undefined
  3. Not an empty String ''
  4. Not an empty Object {} [] (Array is an Object)

Function:

function isEmpty(arg){
  return (
    arg == null || // Check for null or undefined
    arg.length === 0 || // Check for empty String (Bonus check for empty Array)
    (typeof arg === 'object' && Object.keys(arg).length === 0) // Check for empty Object or Array
  );
}

Return true for:

isEmpty(''); // Empty String
isEmpty(null); // null
isEmpty(); // undefined
isEmpty({}); // Empty Object
isEmpty([]); // Empty Array

Here's a simpler(short) solution to check for empty variables. This function checks if a variable is empty. The variable provided may contain mixed values (null, undefined, array, object, string, integer, function).

function empty(mixed_var) {
 if (!mixed_var || mixed_var == '0') {
  return true;
 }
 if (typeof mixed_var == 'object') {
  for (var k in mixed_var) {
   return false;
  }
  return true;
 }
 return false;
}

//   example 1: empty(null);
//   returns 1: true

//   example 2: empty(undefined);
//   returns 2: true

//   example 3: empty([]);
//   returns 3: true

//   example 4: empty({});
//   returns 4: true

//   example 5: empty(0);
//   returns 5: true

//   example 6: empty('0');
//   returns 6: true

//   example 7: empty(function(){});
//   returns 7: false

It depends on what you mean by "empty". The most common pattern is to check to see if the variable is undefined. Many people also do a null check, for example:
if (myVariable === undefined || myVariable === null)...

or, in a shorter form:
if (myVariable || myVariable === null)...


A more readable version of @SJ00 answer:

/**
 * Checks if a JavaScript value is empty
 * @example
 *    isEmpty(null); // true
 *    isEmpty(undefined); // true
 *    isEmpty(''); // true
 *    isEmpty([]); // true
 *    isEmpty({}); // true
 * @param {any} value - item to test
 * @returns {boolean} true if empty, otherwise false
 */
function isEmpty(value) {
    return (
        value === null || // check for null
        value === undefined || // check for undefined
        value === '' || // check for empty string
        (Array.isArray(value) && value.length === 0) || // check for empty array
        (typeof value === 'object' && Object.keys(value).length === 0) // check for empty object
    );
}

If you're looking for the equivalent of PHP's empty function, check this out:

function empty(mixed_var) {
  //   example 1: empty(null);
  //   returns 1: true
  //   example 2: empty(undefined);
  //   returns 2: true
  //   example 3: empty([]);
  //   returns 3: true
  //   example 4: empty({});
  //   returns 4: true
  //   example 5: empty({'aFunc' : function () { alert('humpty'); } });
  //   returns 5: false

  var undef, key, i, len;
  var emptyValues = [undef, null, false, 0, '', '0'];

  for (i = 0, len = emptyValues.length; i < len; i++) {
    if (mixed_var === emptyValues[i]) {
      return true;
    }
  }

  if (typeof mixed_var === 'object') {
    for (key in mixed_var) {
      // TODO: should we check for own properties only?
      //if (mixed_var.hasOwnProperty(key)) {
      return false;
      //}
    }
    return true;
  }

  return false;
}

http://phpjs.org/functions/empty:392


See http://underscorejs.org/#isEmpty

isEmpty_.isEmpty(object) Returns true if an enumerable object contains no values (no enumerable own-properties). For strings and array-like objects _.isEmpty checks if the length property is 0.


_x000D_
_x000D_
function isEmpty(variable) {_x000D_
  const type = typeof variable_x000D_
  if (variable === null) return true_x000D_
  if (type === 'undefined') return true_x000D_
  if (type === 'boolean') return false_x000D_
  if (type === 'string') return !variable_x000D_
  if (type === 'number') return false_x000D_
  if (Array.isArray(variable)) return !variable.length_x000D_
  if (type === 'object') return !Object.keys(variable).length_x000D_
  return !variable_x000D_
}
_x000D_
_x000D_
_x000D_


Combining answers from @inkednm into one function:

   function isEmpty(property) {
      return (property === null || property === "" || typeof property === "undefined");
   }

I see potential shortcomings in many solutions posted above, so I decided to compile my own.
Note: it uses Array.prototype.some, check your browser support.

Solution below considers variable empty if one of the following is true:

  1. JS thinks that variable is equal to false, which already covers many things like 0, "", [], and even [""] and [0]
  2. Value is null or it's type is 'undefined'
  3. It is an empty Object
  4. It is an Object/Array consisting only of values that are empty themselves (i.e. broken down to primitives each part of it equals false). Checks drill recursively into Object/Array structure. E.g.

    isEmpty({"": 0}) // true
    isEmpty({"": 1}) // false
    isEmpty([{}, {}])  // true
    isEmpty(["", 0, {0: false}]) //true
    

Function code:

/**
 * Checks if value is empty. Deep-checks arrays and objects
 * Note: isEmpty([]) == true, isEmpty({}) == true, isEmpty([{0:false},"",0]) == true, isEmpty({0:1}) == false
 * @param value
 * @returns {boolean}
 */
function isEmpty(value){
  var isEmptyObject = function(a) {
    if (typeof a.length === 'undefined') { // it's an Object, not an Array
      var hasNonempty = Object.keys(a).some(function nonEmpty(element){
        return !isEmpty(a[element]);
      });
      return hasNonempty ? false : isEmptyObject(Object.keys(a));
    }

    return !a.some(function nonEmpty(element) { // check if array is really not empty as JS thinks
      return !isEmpty(element); // at least one element should be non-empty
    });
  };
  return (
    value == false
    || typeof value === 'undefined'
    || value == null
    || (typeof value === 'object' && isEmptyObject(value))
  );
}

Check for undefined:

if (typeof response.photo == "undefined")
{
    // do something
}

This would do the equivelant of vb's IsEmpty. If myvar contains any value, even null, empty string, or 0, it is not "empty".

To check if a variable or property exists, eg it's been declared, though it may be not have been defined, you can use the in operator.

if ("photo" in response)
{
    // do something
}