Borislav Hadzhiev
Wed Oct 20 2021·2 min read
Photo by Lukas L
The "startsWith is not a function" error occurs when we call the
startsWith()
method on a value that is not a string. To solve the error,
convert the value to a string using the toString()
method or make sure to only
call the startsWith
method on strings.
Here is an example of how the error occurs.
const str = 123; // ⛔️ TypeError: startsWith is not a function const result = str.startsWith('1');
We called the String.startsWith method on a number and got the error back.
To solve the error, make sure to only call the startsWith()
method on strings.
You can convert most values to a string by using the toString()
method.
const str = 123; const result = str.toString().startsWith('1'); console.log(result); // 👉️ true
Alternatively, you can check if the value is a string before calling the
startsWith()
method.
const str = null; const result = typeof str === 'string' ? str.startsWith('a') : false; console.log(result); // 👉️ false
We used a ternary operator to check if the str
variable stores a string.
If it does, the value to the left of the comma is returned, otherwise the value to the right is returned.
startsWith
method on it, otherwise we return false
.If you want to check if all strings in an array start with a specific substring,
you can use the every
method to iterate over the array and then call the
startsWith
method on each string.
const arr = ['ab', 'ac', 'ad']; const result = arr.every(str => str.startsWith('a')); console.log(result); // 👉️ true
every
method takes a function and calls the function on each element in the array until the function returns a falsy value or we iterate over the entire array.On each iteration, we call the startsWith
method on the string and return the
result.
If the error persists, console.log
the value you're calling the startsWith
method on and check it's type using the typeof
operator.
If the value is an object, there's a very good chance that you are forgetting to
access a specific property on which you need to call the startsWith()
method.