views:

81

answers:

1

I need to check the type of a variable in JavaScript. I know 3 ways to do it:

  1. instanceof operator: if(a instanceof Function)

  2. typeof operator: if(typeof a=="function"

  3. toString method (jQuery uses this): Object.prototype.toString.call(a) == "[object Function]"

Which is the most accurate way to do type checking beetween these solutions? And why? Please don't tell me that the last solution is better only because jQuery uses that.

+1  A: 

How about my home brew function to determine variable 'type'? It can also determine the type of custom Objects:

function whatType(somevar){
    return String(somevar.constructor)
            .split(/\({1}/)[0]
            .replace(/^\n/,'').substr(9);
}
var num = 43
    ,str = 'some string'
    ,obj = {}
    ,bool = false
    ,customObj = new (function SomeObj(){return true;})();

alert(whatType(num)); //=>Number
alert(whatType(str)); //=>String
alert(whatType(obj)); //=>Object
alert(whatType(bool)); //=>Boolean
alert(whatType(customObj)); //=>SomeObj

Based on the constructor property of variables you could also do:

function isType(variable,type){
 if ((typeof variable).match(/undefined|null/i) || 
       (type === Number && isNaN(variable)) ){
        return variable
  }
  return variable.constructor === type;
}
/** 
 * note: if 'variable' is null, undefined or NaN, isType returns 
 * the variable (so: null, undefined or NaN)
 */

alert(isType(num,Number); //=>true

Now alert(isType(customObj,SomeObj) returns false. But if SomeObj is a normal Constructor function, it returns true.

function SomeObj(){return true};
var customObj = new SomeObj;
alert(isType(customObj,SomeObj); //=>true
KooiInc
Are you certain that this works in all browsers?
Sean Kinsey
As far as I tested (A-grade browsers): yes.
KooiInc