DR01D
DR01D

Reputation: 1365

Why is typeof an operator instead of a property?

I'm learning Javascript and I ran across something that feels kind of "quirky".

Why isn't typeof a property like .length or .name? It seems like it should be in that category. Instead it's considered an operator sort of like an equals sign =

Maybe there is an obvious explanation or I'm not understanding something (easily possible).

Upvotes: 3

Views: 68

Answers (2)

Scott Marcus
Scott Marcus

Reputation: 65883

Since typeof is universal in JavaScript (that is, you can use it against any variable), it could have been implemented as a property on Object. But, if it were, you wouldn't be able to call it on null and undefined types.

if(someNullVariable.typeof . . .) { . . . } // error

But, because it is an operator, you can use it independent of what you are checking:

if(typeof someNullVariable === "null")  { . . . }  // Match!

Upvotes: 2

Quentin
Quentin

Reputation: 944568

If it was a property, then you wouldn't be able to test if something was undefined since undefined values can't have properties.

Worse, if a variable was undeclared, then trying to test a property on it would throw a ReferenceError.

Upvotes: 9

Related Questions