3 ms·
A somewhat more succinct option could be to coerce to Object and then use instanceof: 'Object(x) instanceof String'. Or you could use Object.getPrototypeOf, wh
by comex 10y ago
A somewhat more succinct option could be to coerce to Object and then use instanceof: 'Object(x) instanceof String'. Or you could use Object.getPrototypeOf, which coerces to Object automatically these days. But null and undefined are special: calling Object on them returns {}, and calling Object.getPrototypeOf on them throws.
If the type you're testing for is not one of the builtin literal types, you can just use instanceof.
- kbenson 10y ago"Object(foo) instanceof Class" does seem to be the most definitive, but unfortunately seems to require specific testing against a literal that must exist or it throws, and doesn't work for null/undefined. That at least brings the things I need to know to check the type of something down to three, two of which are singular special cases (if somewhat common ones), so that's better and possibly adequate, if not what I would consider good. Then again, I'm not sure I'm capable of thinking it could achieve good while there exists both an undefined and null in the language. It still boggles my mind that it has both.
- comex 10y agoTo clarify, by "literal that must exist or it throws" you mean that you don't know whether the class you're testing for exists? Testing against an invalid class would be an error in most languages… I guess an alternative is foo.constructor and foo.constructor.name, which will give you a string if you want that.
- kbenson 10y agoSince many different js libraries may be loaded from many different sources, I could envision a situation where some utility functions may want to support different inputs depending on what's passed in, and what's passed in might depend on what's loaded, and what's loaded can change at runtime. That's why many dynamic languages allow access to the type through a string representation.