Checking Types
Sometimes we want to check the type of a value at runtime.
For primitive types and functions, we do this by accessing the name of the type using the typeof
keyword.
For object types, there isn't a single best approach, but we'll look at a couple.
Primitive type names
We can find the type name of a primitive or function value using the typeof
operator:
Checking object types
We typically use the instanceof
operator to compare an object value with its constructor.
However, there are some edge cases where we may rely on special library methods like Array.isArray
instead.
Object type names
Generally we should use instanceof
, but we can find the type name of an object value if we really want to.
Note that this runs much more slowly than
typeof
orinstanceof
.