How to Solve endsWith is not a Function in JavaScript
In this tutorial, we are going to learn about how to solve the TypeError: endsWith is not a function in JavaScript.
When we use a ‘endsWith()’ method on a value which is not a data type string we will get the following error in our console.
Example:
const value = 234;
console.log(value.endsWith('4'));
Output:
"TypeError: value.endsWith is not a function
In the example above, we are getting the error because we are using the ‘endsWith()’ method on a datetype number.
To solve the “TypeError: endsWith is not a function”, make sure to call the endsWith() method on a data type string or convert the number to string before calling the endsWith() method on it.
Here is an example:
const value = 234;
const result = value.toString().endsWith('4');
console.log(result);
Output:
True
In the example above, we first converted the given value to a string using the toString() method, then we called a endsWith() method on it.
Note: The ‘endsWith()’ method of the string checks whether it endss with a particular character or not. If it matches with the specified string it returns True otherwise it returns False.
Type checking
To avoid the run time errors, we can also check the given datatype is a string or not before calling the endsWith() method on it.
Here is an example:
const value = 234;
if(typeof value === 'string'){
console.log(value.endsWith('4'));
}else{
console.log('Given value is not a string');
}
Conclusion
The “TypeError: endsWith is not a function” error occurs, when we call a endsWith() method on a value which is not string. To solve the error convert the value to an string before calling the endsWith() method on it or make sure to use the endsWith() method on a valid strings.