Solve - startsWith is not a function Error in JavaScript

avatar

Borislav Hadzhiev

Wed Oct 20 20212 min read

banner

Photo by Lukas L

Solve - startsWith is not a function Error #

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.

typeerror startswith is not a function

Here is an example of how the error occurs.

index.js
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.

index.js
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.

index.js
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.

If the value is a string, we return the result from calling the 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.

index.js
const arr = ['ab', 'ac', 'ad']; const result = arr.every(str => str.startsWith('a')); console.log(result); // 👉️ true
The 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.

Use the search field on my Home Page to filter through my more than 1,000 articles.