If we call the startsWith()
method on the value that is not of a string type, JavaScript will throw a TypeError: startsWith is not a function.
In this tutorial, we will look at what is TypeError: startsWith is not a function error and how to resolve them with examples.
What is TypeError: startsWith is not a function error?
Let us take a simple example to demonstrate this issue
const str = 12345
const output = str.startsWith('123')
console.log(output)
Output
TypeError: str.startsWith is not a function
In the above example, we have declared a variable and assigned the integer value into it.
In the next statement, we call the String.startsWith()
method on the value of the type number, and hence we get a TypeError: startsWith is not a function.
We can also check the variable type using typeof()
to confirm the datatype.
const str = 12345
console.log("The type of variable is",typeof str)
Output
The type of variable is number
How to fix TypeError: startsWith is not a function error?
The String.startsWith()
method can only be used on the string values and not on any other types.
There are two ways to fix this issue in JavaScript.
Solution 1: Convert the value into a string
We can easily resolve the issue by converting the value into a string before calling the startsWith()
method.
If we know the value can be converted to a valid string, then we can use the toString()
method in JavaScript that returns the string representing the object.
Let us take an example to resolve the issue using the toString()
method.
const str = 12345
// Convert to string and then call startsWith()
const output = str.toString().startsWith('123')
console.log(output)
Output
true
Solution 2 – Performing the type check
We can also perform a type check on the variable to check if it’s a string before calling the startsWith()
method.
Example – Type check using if/else
const str = "Hello World"
if (typeof str === 'string') {
// Convert to string and then call startsWith
const output = str.startsWith('Hello')
console.log(output)
}
else {
console.log("The object is not a valid string")
}
Output
true
Example – Type check using ternary operator
const str = "Hello World"
// Convert to string and then call startsWith
const result = typeof str === 'string' ? str.startsWith('Hello') : "";
console.log(result)
Output
true
Conclusion
The TypeError: startsWith is not a function occurs if we call a startsWith()
method on the value that is not of a type string. We can resolve the issue by converting the value into string before calling the startsWith()
method or by performing a type check; we can mitigate this error.