Sometimes, we may run into the ‘TypeError: "x" is not a function’ when we’re developing JavaScript apps.
In this article, we’ll look at how to fix the ‘TypeError: "x" is not a function’ when we’re developing JavaScript apps.
Fix the ‘TypeError: "x" is not a function’ When Developing JavaScript Apps
To fix the ‘TypeError: "x" is not a function’ when we’re developing JavaScript apps, we should make sure the value that we’re calling is a function.
For instance, we shouldn’t call methods on an object that doesn’t have the method:
let obj = {a: 1, b: 3, c: 4};
obj.map((num) => {
return num * 2;
});
obj
is an object, so it doesn’t have the map
method unless we added one into the object.
Since we didn’t have that, the error will be thrown.
Instead, we call map
on an array, which has the map
method:
let numbers = [1, 4, 9];
numbers.map((num) => {
return num * 2;
});
We should also look out for typos in our code to prevent this error.
Also, we should make sure a method doesn’t share a name with a pre-existing property.
For instance, instead of writing:
const Dog = function () {
this.age = 11;
this.color = "black";
this.name = "Jane";
return this;
}
Dog.prototype.name = function(name) {
this.name = name;
return this;
}
const myNewDog = new Dog();
myNewDog.name("Cassidy");
which will thrown this error since name
is a pre-existing property and it’s not a function, we write:
const Dog = function () {
this.age = 11;
this.color = "black";
this.dogName = "Jane";
return this;
}
Dog.prototype.name = function(name) {
this.dogName = name;
return this;
}
const myNewDog = new Dog();
myNewDog.name("Cassidy");
If we have an arithmetic expression where we multiply something with an expression with parentheses, we should make sure we have the *
operator.
So instead of writing:
const sixteen = 2(3 + 5);
which will throw the error since 2 isn’t a function, we write:
const sixteen = 2 * (3 + 5);
which does the multiplication like we expected.
Conclusion
To fix the ‘TypeError: "x" is not a function’ when we’re developing JavaScript apps, we should make sure the value that we’re calling is a function.
We should also look out for typos in our code to prevent this error.
Also, we should make sure a method doesn’t share a name with a pre-existing property.
If we have an arithmetic expression where we multiply something with an expression with parentheses, we should make sure we have the *
operator.