Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    New Coder
    Join Date
    Mar 2012
    Posts
    14
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Empty function script

    (I did indeed read the rules of this forum and while I'm not a "seasoned" javascript coder I thought that this script was simple enough to not matter. If that is unacceptable I apologize and you can feel free to delete this post)

    Here is a function that allows you to use a PHP like 'empty()' function. It helped me a lot because it combines several other JS functions into one neat package.

    Code:
    function empty(obj) {
        if (typeof obj == 'undefined' || obj === null || obj === '') return true;
        if (typeof obj == 'number' && isNaN(obj)) return true;
        if (obj instanceof Date && isNaN(Number(obj))) return true;
        return false;
    }
    Hope this helps people as much as it helps me!

  • #2
    Regular Coder Nile's Avatar
    Join Date
    Jun 2008
    Posts
    280
    Thanks
    2
    Thanked 46 Times in 46 Posts
    You can be less repetitive like this:
    Code:
    function empty(obj){
       return (typeof obj == 'undefined' || obj === null || obj === '') || (typeof obj == 'number' && isNaN(obj)) || (obj instanceof Date && isNaN(Number(obj)));
    }

  • #3
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,380
    Thanks
    11
    Thanked 592 Times in 572 Posts
    Quote Originally Posted by Nile View Post
    You can be less repetitive like this:
    Code:
    function empty(obj){
       return (typeof obj == 'undefined' || obj === null || obj === '') || (typeof obj == 'number' && isNaN(obj)) || (obj instanceof Date && isNaN(Number(obj)));
    }
    you can be less repetitive and properly handle arrays and objects like this :
    Code:
    function empty(obj){
       var u;
       if((''+obj)==="[object Object]"){for(var i in obj);return !i;}
       return  !+obj && (!{'0':1,false:1}[obj] );
    }
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/9/03) IE7:0.1, IE8:4.6, IE11:9.1, IE9:3.1, IE10:3.0, FF:17.2, CH:46, SF:11.4, NON-MOUSE:38%

  • #4
    Moderator
    Join Date
    May 2002
    Location
    Hayward, CA
    Posts
    1,461
    Thanks
    1
    Thanked 23 Times in 21 Posts
    I actually prefer Nile's version here, because it's more readable.
    "The first step to confirming there is a bug in someone else's work is confirming there are no bugs in your own."
    June 30, 2001
    author, Verbosio prototype XML Editor
    author, JavaScript Developer's Dictionary
    https://alexvincent.us/blog


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •