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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
mck89
  • 18,918
  • 16
  • 89
  • 106
  • Pretty much duplicate of http://stackoverflow.com/questions/899574/which-is-best-to-use-typeof-or-instanceof – cletus May 12 '10 at 08: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 – mck89 May 12 '10 at 08:07
  • Secure? Do you mean accurate? – kennytm May 12 '10 at 08:08
  • The thread linked by cletus answers your accuracy question. – Kevin May 12 '10 at 08:12
  • But the last solution is not mentioned – mck89 May 12 '10 at 08:14
  • @mck89 If you mean accurate and not secure, please edit the question to reflect this. – Mathew May 12 '10 at 08:31
  • Sometimes duck-typing is more appropriate than all the ones you mentioned. It's probably more code to write, but seems more reliable. Think about an object like jQuery that has a `length` property. You can then transform the jQuery instance into an Array instance and then call Array methods on it. – Ionuț G. Stan May 12 '10 at 09:12

1 Answers1

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
KooiInc
  • 119,216
  • 31
  • 141
  • 177