Sometimes, we may run into the ‘TypeError: "x" is not a constructor’ when we’re developing JavaScript apps.
In this article, we’ll look at how to fix the ‘TypeError: "x" is not a constructor’ when we’re developing JavaScript apps.
Fix the ‘TypeError: "x" is not a constructor’ When Developing JavaScript Apps
To fix the ‘TypeError: "x" is not a constructor’ when we’re developing JavaScript apps, we should make sure we’re using the new
operator on a constructor function or class.
Similar errors we may see include:
TypeError: Math is not a constructor
TypeError: JSON is not a constructor
TypeError: Symbol is not a constructor
TypeError: Reflect is not a constructor
TypeError: Intl is not a constructor
TypeError: Atomics is not a constructor
For instance, the following code will throw this error:
const Car = 1;
new Car();
new Math();
new Symbol();
function* f() {};
const obj = new f;
In the first example, Car
is a number, so we can’t use the new
operator on it to create a new Car
instance.
Likewise, Math
and Symbol
aren’t constructors or classes, so we can’t use the new
operator on them.
In the last example, f
is a generator function, which isn’t the same as a constructor function or class, so we can’t use new
on it to create a new f
instance.
To make Car
a constructor, we write:
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
We can also write:
class Car {
constructor(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
}
They’re equivalent.
constructor
takes arguments for the constructor function like the constructor function does.
Then we assign the values to instance variables inside the constructor or class.
Conclusion
To fix the ‘TypeError: "x" is not a constructor’ when we’re developing JavaScript apps, we should make sure we’re using the new
operator on a constructor function or class.