Why is it called TypeError in JavaScript? - kdaisho/Blog GitHub Wiki
If I create an object, e.g.,
const user = {
name: 'me',
address: {
apt: 302,
st: 'Tim Hortons'
}
}
then if I try user.address2.apt
, it throws TypeError.
TypeError: Cannot read properties of undefined (reading 'apt')
Why is this error called "Type" error? Is it related to type?
The answer is yes.
The TypeError is thrown because the type of user.address2 is undefined
, and you cannot access properties on undefined. This is why it is called a "Type" error; it indicates that the operation is not valid for the type of the value you are working with.
Remember, JavaScript is a dynamically typed language. It does have a concept of types, such as undefined
, null
, boolean
, number
, string
, object
, bigint
and symbol
. These types are checked at runtime, and certain operations are only valid for certain types.
When you encounter a TypeError in JavaScript, it indicates that an operation was attempted on a value of an inappropriate type.
So that's why this type of error is called "TypeError".