Sometimes, we may run into the ‘TypeError: invalid ‘instanceof’ operand "x"’ when we’re developing JavaScript apps.
In this article, we’ll look at how to fix the ‘TypeError: invalid ‘instanceof’ operand "x"’ when we’re developing JavaScript apps.
Fix the ‘TypeError: invalid ‘instanceof’ operand "x"’ When Developing JavaScript Apps
To fix the ‘TypeError: invalid ‘instanceof’ operand "x"’ when we’re developing JavaScript apps, we should make sure we’re using the instanceof
operator on a constructor or class.
On Firefox, the error message for this error is TypeError: invalid 'instanceof' operand "x"
or TypeError: "x" is not a function
.
And on Chrome, the error message for this error is TypeError: Right-hand side of 'instanceof' is not an object
or TypeError: Right-hand side of 'instanceof' is not callable
.
For instance, the following code will all throw this error since the right operand of instanceof
aren’t a constructor or class:
"test" instanceof "";
42 instanceof 0;
function Foo() {}
const f = Foo();
const x = new Foo();
x instanceof f;
x instanceof x;
To fix this, we write:
typeof "test" == "string";
typeof 42 == "number"
function Foo() {}
const f = Foo;
const x = new Foo();
x instanceof f;
x instanceof Foo;
We use the typeof
operator to test for primitive types.
And we use instanceof
with Foo
without calling to check if x
is an instance of Foo
.
Conclusion
To fix the ‘TypeError: invalid ‘instanceof’ operand "x"’ when we’re developing JavaScript apps, we should make sure we’re using the instanceof
operator on a constructor or class.
On Firefox, the error message for this error is TypeError: invalid 'instanceof' operand "x"
or TypeError: "x" is not a function
.
And on Chrome, the error message for this error is TypeError: Right-hand side of 'instanceof' is not an object
or TypeError: Right-hand side of 'instanceof' is not callable
.