I am reading this book called YDKJS and it's mentioned that:
typeof null
is an interesting case, because it errantly returns"object"
, when you'd expect it to return"null"
.Warning: This is a long-standing bug in JS, but one that is likely never going to be fixed. Too much code on the Web relies on the bug and thus fixing it would cause a lot more bugs!
I can't wrap my head around any code that makes use of the return type of a null
. Can anyone please give some example use cases?
It's not that they make use of return type of a null
, but the return type of a variable.
What I mean is that there are so many cases where devs are writting:
if (typeof something === "object"){
}
And expect whatever passes this condition to be, among others, null
as well.
So they rely on the fact that whatever relies in that block of true
statement to hold even a null
value.
Let's say we have this piece of code:
switch (typeof something) {
case "object":
if (something) {
doSomethingWithObject(something);
} else {
rejectTransaction(); // we have null
}
break;
case "undefined":
throwAMeaningfulError();
break;
default:
doSomethingWithNumberOrString(something);
break;
}
As can be seen, we're handling all cases, be it object
, undefined
, string
, number
or null
.
If this bug would be fixed, and typeof null
would return null
, the rejectTransaction
would never be called. Instead, the doSomethingWithNumberOrString
would be called.
I'm not saying this is a good example of code, but something that might be out there that might break because devs relied on the fact that typeof null
returned "object"
and not "null"