typeof null

Jorge jorge at jorgechamorro.com
Wed May 9 16:47:01 PDT 2012

On May 10, 2012, at 1:08 AM, Axel Rauschmayer wrote:

>>> Are we going to have RegExp.isRegExp() and Date.isDate() and Number.isNumber() etc. too ?
>> I did wince a bit about ES5's Array.isArray -- perhaps since it takes any x and tells whether x is an Array (from any window or frame) instance, it should have gone on object. You're right that the instanceof limitation motivating Array.isArray applies to these and other built-in "classes" as well.
>> Do we just add 'em all, or try to add only the ones for which we have enough experience to hope we're actually helping developers? How many times have you wanted RegExp.isRegExp, say? The belief is that testing for array-ness is more common. I don't have data, though, so I'm uncomfortable with any "need-based" approach.
>> Adding lots of predicates is straightforward, but then the dialectic requires us to wince at the sheer number of predicates (and the redundant name stems), and try for something like what Axel suggested: a do-it-all "type" or "typeOf" or "classify" API.
>> Comments welcome. I'm not sure what is best but lean toward predicates as goods in themselves, even if not the complete solution (if there is a complete solution).
> It would be great if we could eliminate these predicates completely. How often does the frame crossing problem matter in practice? It doesn’t show up in non-browser environments, right?
> I see several possibilities:
> - Make instanceof work correctly with objects that have crossed frames.
> - Introduce a binary predicate, e.g. likeInstanceOf that correctly handles cases where the lhs and rhs come from different contexts/frames.
> Additionally, one could throw an exception if there is an instanceof check whose lhs and rhs are from different contexts (failing fast, preventing obscure and hard-to-debug errors).

When you want to dispatch based on a type, a fixed typeof (one that worked well) would be better:

switch (typeof x)

case "Array":

case "RegExp":

case ...

else you'd have to do:

if (Array.isArray(x)) ...
else if (RegExp.isRegExp(x)) ...
else if ( etc )

When you just want to assert that x is of type Type, then an if (Type.isType(x)) would be ok, but a proper typeof would do just as well: if (typeof x === "Type")

So it seems that a new, fixed typeof would be best?

And if the new, fixed typeof were typeOf(), with capital O, a global function instead of a language keyword/operator? That would be easily polyfill-able.

More information about the es-discuss mailing list