JavaScript

TypeError: startsWith is not a Function in JavaScript

The String type object in JavaScript has a method called the “startsWith()” method that can be utilized to verify whether a string starts with a particular character. If you apply this method to any other type to verify whether it starts with the specified non-string parameter, it will throw an error.

This tutorial will discuss:

How Does the “TypeError: startsWith is not a Function in JavaScript” Error Occur?

JavaScript throws a “TypeError: startsWith is not a function” if the “startsWith()” method is called on a value that is not of the string type. Let’s see an example to justify the added statement.

Example

Here, first, we will create a variable that stores a number:

const string = 927354138;

Call the “startWith()” method and pass “9” as a string argument to check whether the string starts with “9”:

const startStr = string.startsWith('9');

Print the result on the console:

console.log(startStr);

It can be observed that we have encountered the discussed error as the “startsWith()” method is called on a string type value:

How to Fix the “TypeError: startsWith is not a Function in JavaScript” Error?

To fix the error, use the “toString()” method with the “startsWith()” method. The toString() method will convert the input value into string type because the startsWith() method only accepts the string type values as argument.

Syntax

Use the below-provided syntax to fix the error:

toString().startsWith(searchString)

The “searchString” is the character that has to be found at the start of the string.

Return Value

  • The “toString()” method returns a string representing the object.
  • The “startsWith()” method returns “true” if the “searchString” is at the beginning of the string else, it returns “false”.

Example

Call the startsWith() method with the “toString()” method that will convert the input into the string:

const startStr = string.toString().startsWith('9');

Output

We have provided the necessary information related to the stated error and the relevant solution.

Conclusion

The “TypeError: startsWith is not a function” occurs when the method is called on the non-string type values, as the “startsWith()” method is only used for the string type values. So, to fix this error, use the “toString()” method with the startsWith() method for converting the specified value into the string type before further processing. In this tutorial, we defined the reason behind the stated error and the method to fix it.

About the author

Farah Batool

I completed my master's degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.