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));
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));
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));
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);
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"));
Maybe you are interested:
- TypeError: querySelectorAll is not a function in JS
- TypeError (intermediate value)(…) is not a function in JS
Name of the university: HCMUT