Author -  Sai gowtham

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.

Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2023 (Beginner + Advanced)
JavaScript - The Complete Guide 2023 (Beginner + Advanced)
116,648 students enrolled
52 hours of video content
$14.99 FROM UDEMY
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
631,582 students enrolled
49 hours of video content
$24.99 FROM UDEMY
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
203,937 students enrolled
31.5 hours of video content
$14.99 FROM UDEMY