The problem is that more than just {} returns an object type
typeof 5 == 'number' typeof NaN == 'number' typeof 'test' == 'string' typeof true == 'boolean' typeof undefined == 'undefined' typeof null == 'object' typeof /asdf/ == 'object' // this is true in some engines, like Firefox's. Not in V8 (in which it is 'function') typeof [] == 'object' typeof {} == 'object'
But using toString, you can additionally check:
toString.call(null) == '[object Window]' // or '[object global]' or '[object Null]' - depends on engine toString.call(/asdf/) == '[object RegExp]' toString.call([]) == '[object Array]' toString.call({}) == '[object Object]'
So the best way to check:
var test; test = {}; typeof test == 'object' && toString.call(test) == '[object Object]'; // true test = []; typeof test == 'object' && toString.call(test) == '[object Object]'; // false // et cetera
Hope that helps
source share