...

View Full Version : Empty function script



Darkranger85
03-25-2012, 09:25 PM
(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.



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! :)

Nile
03-26-2012, 02:22 AM
You can be less repetitive like this:


function empty(obj){
return (typeof obj == 'undefined' || obj === null || obj === '') || (typeof obj == 'number' && isNaN(obj)) || (obj instanceof Date && isNaN(Number(obj)));
}

rnd me
03-26-2012, 02:08 PM
You can be less repetitive like this:


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 :

function empty(obj){
var u;
if((''+obj)==="[object Object]"){for(var i in obj);return !i;}
return !+obj && (!{'0':1,false:1}[obj] );
}

Alex Vincent
03-26-2012, 07:39 PM
I actually prefer Nile's version here, because it's more readable.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum