05 November 2011

Javascript function for checking a variables type or empty/unset variables - similar to PHP's empty()

I've been building on this one all week and I'm finding it more and more useful for quickly writing variable checks at the top of functions. You can use it to easily check if a var is defined or check if it is of a certain type. It's a work in progress but it's very handy. Check out the commented examples to get an idea of potential uses. Ideas for improvements/additions are welcome!

Please see note before copying my code>>

//CHECK TYPE OF PASSED OBJ:
function is(obj,type){
 switch(type){
  case 'array': case 'ar': //ARRAY:
   return(String(obj.constructor).indexOf('Array')>-1)
  break;
  case 'integer': case 'int': case 'number': //NUMBER:
   return((parseFloat(obj) == parseInt(obj)) && !isNaN(obj))
  break;
  default: //IS EMPTY:
   if(obj==null || obj==undefined || obj==' ' || obj==0 || obj==false || obj=="false" || obj=='' || obj=="\n") return(false);
   return(true)
 }
}
/*EXAMPLES:
returns true if myvar is a positive value (string, number, array, DOM element, etc):
if(is(myvar)){..continue with function...}

returns true if myvar is an array:
if(is(myvar,'array')){..continue with function...}

returns true if myvar is an integer or can be converted to an integer:
if(is(myvar,'int')){..continue with function...}
*/


//CHECKS IF ANY OF THE PASSED ARG(S) ARE BLANK OR FALSE OR 0 OR UNDEFINED:
function isempty(){
 for (var i = 0; i < arguments.length; i++) {
  if(!is(arguments[i])){return(true)}
 }  
 return(false)
}
/*EXAMPLE:
if(isempty(requiredVar1,requiredVar2,requiredVar3)){
       return(false);
}else{...continue with function...}
*/ 

5 comments:

  1. This site is excellent and so is how the subject matter was explained. I also like some of the comments too. Waiting for the next post. Welcome go to my site 192.168.l.l

    ReplyDelete
  2. now we are here to help you to overcome your obstetric problems.

    Biaya Aborsi

    ReplyDelete
  3. I have read your article, it is very informative and helpful for me. I admire the valuable information you offer in your articles. Thanks for posting it.

    mycherrycreek
    VST torrent
    xvideostudio video editor apk free download for pc full version
    How many teaspoons in a tablespoon
    New Social Bookmarking Site

    ReplyDelete
  4. The timeless case shape, the black-and-white dial and white baton hands for superb readability, the tried-and-tested hand-wound movement, link and the Plexi (Hesalite) link crystal that magnified the dial all link added up to me wanting one almost desperately.

    ReplyDelete