0

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.

7
  • Pretty much duplicate of stackoverflow.com/questions/899574/… Commented May 12, 2010 at 8:06
  • I'm not looking for differences, i know how they behave. I want to know wich is the most secure solution between them and why Commented May 12, 2010 at 8:07
  • Secure? Do you mean accurate? Commented May 12, 2010 at 8:08
  • The thread linked by cletus answers your accuracy question. Commented May 12, 2010 at 8:12
  • But the last solution is not mentioned Commented May 12, 2010 at 8:14

1 Answer 1

1

[Edit 2023/05/28] See this github repository for a more comprehensive type checker.

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
Sign up to request clarification or add additional context in comments.

1 Comment

As far as I tested (A-grade browsers): yes.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.