Sometimes, we may run into the ‘TypeError: "x" is (not) "y"’ when we’re developing JavaScript apps.
In this article, we’ll look at how to fix the ‘TypeError: "x" is (not) "y"’ when we’re developing JavaScript apps.
Fix the ‘TypeError: "x" is (not) "y"’ When Developing JavaScript Apps
To fix the ‘TypeError: "x" is (not) "y"’ when we’re developing JavaScript apps, we should make sure that we aren’t doing operations that aren’t unexpected for a given data type.
Messages may include:
TypeError: "x" is undefined
TypeError: "x" is null
TypeError: "undefined" is not an object
TypeError: "x" is not an object or null
TypeError: "x" is not a symbol
On Edge, the error message for this error is TypeError: Unable to get property {x} of undefined or null reference
.
And on Firefox, the error message for this error is TypeError: "x" is (not) "y"
.
For instance, we should write code like:
let foo = undefined;
foo.substring(1);
let foo = null;
foo.substring(1);
let foo = {}
Symbol.keyFor(foo);
let foo = 'bar'
Object.create(foo);
We can’t call substring
on foo
since foo
is undefined
.
We also can’t call substring
on a null
value.
In the 3rd example, since foo
is an object, we can’t call Symbol.keyFor
on it to get its content.
And in the last example, foo
is a string, so we can’t call Object.create
with it since an object or null
is expected.
To fix the issue, we can use the typeof
operator to check for the value we expect before we do any operation on it:
To do this, we write:
if (typeof foo !== 'undefined') {
// ...
}
We check if foo
isn’t undefined
with the typeof
operator by checking if typeof
returns 'undefined'
with foo
as its operand.
Conclusion
To fix the ‘TypeError: "x" is (not) "y"’ when we’re developing JavaScript apps, we should make sure that we aren’t doing operations that aren’t unexpected for a given data type.