How To Solve “TypeError: indexOf is not a function” In JavaScript

TypeError indexOf is not a function in JavaScript

TypeError: indexOf is not a functionin JavaScript is a common error related to a string or array object. The below explanations can help you know more about the causes of this error and solutions.

How does the error “TypeError: indexOf is not a function” happen?

Basically, indexOf() is a method that belongs to string and array objects. The error “Indexof is not the function” indicates that the ‘indexOf’ method is called on an object that is not in an array or string type, it may be other types such as numbers, boolean or even object types. However, the null type and undefined types does not return this error when calling this method.

For example, calling the indexOf method on number type will cause this error:

let a = 999999;
console.log(a.indexOf(9));

Output:

Uncaught TypeError: a.indexOf is not a function

Here is another example of using this method on boolean type:

let b = true;
console.log(b.indexOf(false));

Output:

Uncaught TypeError: b.indexOf is not a function

To fix this error, we suggest you convert the variable to an array or a string and then call the function or use another method that your variable type supports instead of indexOf().

How to solve the error?

Method 1: Convert number into a string using + operator

As we have explained above, you must convert a number into an array or a string to use the indexOf method. However, we recommend you convert the number into a string as it is easy to implement.

let a = 987654;
let string = "" + a;
console.log(string.indexOf(4));

Output:

5

We used the approach of concatenating a number with an empty string, which is one of the most efficient ways of converting a number into a string. But remember that this approach will not always return the correct string (if the number is a floating point). For instance:

let a = 123e-45;
let string = "" + a;
console.log(string);

Output:

1.23e-43

Method 2: Convert other types into a string using toString()

Another way to overcome this problem is to convert the time, a number or the object into a string using built-in toString() function

let time = new Date();
let string = time.toString();
console.log(string.indexOf("GMT"));

Output:

25

Summary

We have learned how to deal with the error “TypeError: indexOf is not a function” in JavaScript. You can easily avoid this error by checking the correct type before calling the indexOf() method.

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *