What to Expect From typeof
As JavaScript is loosely typed, it's often necessary to check what type of variable you're dealing with. This is easily done with the typeof operator,
but developers be warned, the results are not always accurate, as you can see in the table below:
| Type | Expected | Actual |
|---|---|---|
Array |
array | object |
Boolean |
boolean | boolean |
Function |
function | function |
null |
null | object |
Number |
number | number |
Object |
object | object |
String |
string | string |
undefined |
undefined | undefined |
Array objects and null variables do not return expected results. You can try this out for yourself here:
This behavior is shared among all of the regular browsers including Firefox, Internet Explorer, Opera and Safari.
[Source: A Survey of the JavaScript Programming Language by Doug Crockford]
An array is an object. So object should be expected for this. I think Crockfords wrong to call this a mistake. Although a function is an object too, the spec (ecma262) makes a special case for functions.
The spec states null should be typeof “object”. Not exactly sure why though. Perhaps because its a null reference, which would point to an object if it wasn’t null. That might sound a bit weak, but again, I’m sure there is logical reasoning for this and its not a “mistake”, like a typo or something.
Well typos are still mistakes right? And the problem with using “object” for arrays is that almost everything in JavaScript is an object. typeof array being “object” is bad for the same reason that typeof function being “function” is good. Ambiguity is not helpful.
Sorry I worded that badly. I meant a typo is a mistake. I’m trying to say that its a bit unfair to just call these things mistakes when a they’re more like debatable decisions by the spec writers. I agree the ambiguity isn’t great. Function being typeof “function” is a strange one. Perhaps this should be “object” too. We have instanceof for determining exactly what object something is.
Ah, I see what you’re saying. Yes, Crockford’s style is very rigid, very black and white. For the record, I agree with most of what he preaches. But he often declares things as “incorrect” or “a mistake” when they’re sometimes just curious or unexpected. They’re not always necessarily wrong, just maybe odd.
Actually I’ve been rewriting this particular article since I read his book JavaScript: The Good Parts. It’s now about three times as long and offers workarounds for when typeof is not helpful. Hopefully I’ll have that done soon.
Agreed :) Looking forward to the update
[...] Fuente: scriptNode [...]