TypeError: "x" is (not) "y"
The JavaScript exception "x is (not)y" occurs when there was anunexpected type. Oftentimes, unexpectedundefined
ornull
values.
Message
TypeError: Cannot read properties of undefined (reading 'x') (V8-based)TypeError: "x" is undefined (Firefox)TypeError: "undefined" is not an object (Firefox)TypeError: undefined is not an object (evaluating 'obj.x') (Safari)TypeError: "x" is not a symbol (V8-based & Firefox)TypeError: Symbol.keyFor requires that the first argument be a symbol (Safari)
Error type
What went wrong?
There was an unexpected type. This occurs oftentimes withundefined
ornull
values.
Also, certain methods, such asObject.create()
orSymbol.keyFor()
, require a specific type, that must be provided.
Examples
Invalid cases
You cannot invoke a method on anundefined
ornull
variable.
js
const foo = undefined;foo.substring(1); // TypeError: foo is undefinedconst foo2 = null;foo2.substring(1); // TypeError: foo2 is null
Certain methods might require a specific type.
js
const foo = {};Symbol.keyFor(foo); // TypeError: foo is not a symbolconst foo2 = "bar";Object.create(foo2); // TypeError: "foo2" is not an object or null
Fixing the issue
To fix null pointer toundefined
ornull
values, you can test if the value isundefined
ornull
first.
js
if (foo !== undefined && foo !== null) { // Now we know that foo is defined, we are good to go.}
Or, if you are confident thatfoo
will not be anotherfalsy value like""
or0
, or if filtering those cases out is not an issue, you can simply test for its truthiness.
js
if (foo) { // Now we know that foo is truthy, it will necessarily not be null/undefined.}