Check if it is empty regardless of type, javascript

Asked

Viewed 5,603 times

4

I am trying to create a function that checks if you have something blank, empty, Undefined, null etc..

But my difficulty is that I don’t know all the ways a string is "blank"

I created this function

function empty() {
   var args = [].slice.call(arguments);

    args.forEach(function(argument) {
        if(!argument || 0 === argument.length || !argument || /^\s*$/.test(argument) || argument.length === 0 || !argument.trim()) {
            return false;
        } 
    });
}

the intention is to return false so that I can simply check if among my variables there are any blank ones in this way if(!empty(var1, var2...)) {

But there are several ways, as I said, for example in my doubts:

If it is an array, how to know if it is empty?

If it is a JSON how to know if it is empty?

If it’s just numbers, you can tell if it’s empty?

are so many ways you have to check that I get lost..

When I say empty I mean Undefined, null, filled only with empty spaces etc..

  • 1

    Should the zero number validate true or false? What types of values do you have?

  • @Sergio the number itself must refer to false, if it is in a true string..

2 answers

3

There is no "empty" value for numbers and booleans, unless you define some. This "empty" value, in these cases, would be null, or undefined.

I’m assuming that:

  • null is empty;
  • undefined is empty;
  • objects without fields is empty (including inherited);
  • arrays without elements is empty;
  • strings of size 0 are empty;
  • strings formed only by blank characters are empty;
  • there is no specific numerical or boolean value to represent empty (could be 0 or false, maybe).

Thus, it could be written as follows:

function empty() {
    var args = Array.prototype.slice.call(arguments);

    return args.some(function(argument) {
        return argument === null
            || typeof argument === "undefined"
            || (Array.isArray(argument) && argument.length === 0)
            || (typeof argument === "object" && emptyObject(argument))
            || (typeof argument === "string" && (argument.length === 0 || argument.trim().length === 0));
    });
}

function emptyObject(arg) {
    var count = 0;
    for ( var i in arg ) {
        count++;
        break;
    }
    return count === 0;
}

The method emptyObject checks how many fields an object has. I don’t know any other way to do this.

The call to the method Array.some serves so that when a single empty item is found, the method already returns, not checking all other items.

Not tested, so there may be some errors ;D

Improvements are welcome!

  • I managed to have a direction now!! Thank you! , but I have some questions, what did I mean by inherited? I will test the function thoroughly and I answer you..

  • The object being checked if this blank in the method emptyObject can be inherited from another object (POO). In this case, these fields will be considered by the method. Ok, thank you!

2

In Javascript, the fastest way to validate the result of an expression including the most commonly used types of values representing a nonvalue is the double negation. More details on this reply.

The possible values that can suffer Typecast for true/false are:

  • false
  • NaN
  • undefined
  • null
  • "" (empty string)
  • 0

Some examples of validation via double negation (taken of this answer):

          !!false === false
           !!true === true

              !!0 === false
!!parseInt("foo") === false // NaN
              !!1 === true
             !!-1 === true  // -1 é verdadeiro

             !!"" === false // string vazia é 'falsa'
          !!"foo" === true  // string não-vazia é 'verdadeira'
        !!"false" === true  // ...mesmo se conter o valor "false"

     !!window.foo === false // undefined é falso
           !!null === false // null também

             !!{} === true  // um objeto vazio é 'verdadeiro';
             !![] === true  // um array vazio também.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.