Solve - indexOf is not a function Error in JavaScript

avatar

Borislav Hadzhiev

Tue Oct 19 20212 min read

banner

Photo by Roan Lavery

Solve - indexOf is not a function Error in JavaScript #

The "indexOf is not a function" error occurs when the indexOf() method is called on a value that is not of type string or array. To solve the error, convert the value to a string or array before calling the method or make sure to only call the indexOf method on strings or arrays.

typeerror indexof is not a function

Here is an example of how the error occurs.

index.js
const str = 1234; // ⛔️ Uncaught TypeError: str.indexOf is not a function const result = str.indexOf('3');

We called the indexOf method on a number and got the error. The indexOf method is only supported on strings or arrays.

To solve the error, either convert the value to a string or array before calling the method or only call the method if the value is of the correct type.

index.js
// 👇️ For Strings const num = 1234; const result1 = num.toString().indexOf('3'); console.log(result1); // 👉️ 2 // 👇️ For Arrays const set = new Set(['a', 'b', 'c']); const result2 = Array.from(set).indexOf('b'); console.log(result2); // 👉️ 1

In the first example we convert the number to a string using the toString() method before calling the indexOf method.

In the second example, we used the Array.from method to convert a Set to an array before calling the indexOf method.

Alternatively, you can conditionally check if the value is of the correct type before calling the indexOf method.
index.js
const num = 1234; const result1 = typeof num === 'string' ? num.indexOf('3') : -1; console.log(result1); // 👉️ -1 // 👇️ For Arrays const set = new Set(['a', 'b', 'c']); const result2 = Array.isArray(set) ? set.indexOf('b') : -1; console.log(result2); // 👉️ -1

In both examples we used the ternary operator, which is very similar to an if/else statement.

If the expression to the left of the question mark evaluates to a truthy value, the value to the left of the colon is returned, otherwise the value to the right is returned.

In the first example, we check if the value has a type of string. If it does, we return the result of calling the indexOf method on it, otherwise return -1.

In the second example, we check if the value is an array using the Array.isArray method.

If the value is an array, we return the result of calling the indexOf method on it, otherwise return -1.

If the error still persists, console.log the value you're calling theindexOf method on and make sure it's either of type string or array.
Use the search field on my Home Page to filter through my more than 1,000 articles.