Coercion in JavaScript: Types and the typeOf
Operator
The purpose of this series is to better understand the concept of coercion and how it works within the JavaScript programming language. This is often a pain point for many developers and for good reason, but it is good to understand why JavaScript has these odd behaviors when it comes to types since the language takes up such a large space within the programming community.
Types in JavaScript
A good place to start would be to introduce ourselves with the data types of JavaScript. There are two kinds of types, primitive and non primitive:
Primitive vs Non Primitive Types:
The main difference between Primitive and Non-Primitive data types are that primitive types do not have any properties or methods while non primitive data types do. Since JavaScript is a dynamically typed language, variables don’t necessarily have types, but values do. So how do we figure out what the type of a variable’s value is?
typeOf Operator
the typeOf
operator is a tool to determine the identity of something, or type. So if we look below we can see that we are evaluating what is currently inside the variable v.
One important thing to note is that the typeof
operator will always return a string, in fact it can only return a string contained in the enum list which includes: "undefined", "number", "string", "boolean", "object", "bigint", "symbol", "function"
Although there are often cases in JavaScript where the typeOf
operator returns values that we might find unintuitive.
Strange Cases we should learn:
- Here you can see
typeof null
returns “object”. In early versions of JavaScript the docs state that to unset a primitive you should set it toundefined
and to unset an object you should set it tonull.
Developers believe this may be the root causenull
still returns as an object when using thetypeof
operator. - While technically a “function” is not a type, our
typeof
operator still returns the string “function”. This might seem odd, but it is ultimately useful for us. Classes will also return the string “function” in this case. - You may have already noticed earlier that the string “array” was not included in the list of options that the
typeof
operator could return. This is because arrays are subtypes of objects, but there is a way to check if a value is an array with theisArray()
method.
Moving forward:
Understanding the typeof
operator can give us more insight into the quirks of the typing system JavaScript has, next we’ll take a look at the concept of NaN
and the isNaN()
method.