How to fix indexOf is not a function in JavaScript
In this tutorial, we are going to learn about how to fix the TypeError indexOf is not a function in JavaScript
When we use a indexOf()
method on a value which is not an data type string or array we will get the following errors in our console.
Example:
const price = 23.5;
price.indexOf('3');
Output:
"TypeError: price.indexOf is not a function
In the example above, we are getting the error because we are using the indexOf() method on a data type Number. The indexOf()
method is only available for strings and arrays.
To fix the error, convert the given value to a string or array before calling the indexOf()
method on it.
Here is an example:
const price = 23.5;
const result = price.toString().indexOf('3');
console.log(result); // 1
In the example above, we used the toString()
method on a value to convert the Number to a String before calling the indexOf()
method.
We can check if the given value is an type string or array before calling the indexOf() method on it. So that we can avoid the runtime errors.
const price = 23.5;
if (typeof price === "string"){
console.log(price.indexOf('3'));
}else{
console.log("Please check data type");
}
const arr = [2, 3, 4];
if(Array.isArray(arr)){
console.log(arr.indexOf(3)); // 1
}
Conclusion
The “indexOf is not a function” error occurs when we call a indexOf() method on a value other than the strings or arrays. To fix the error convert the value to a string or array before calling the indexOf() method on it.