How to Solve charAt is not a Function in JavaScript
In this tutorial, we are going to learn about how to solve the TypeError: charAt is not a function in JavaScript.
When we use a ‘charAt()’ 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.charAt(2));
Output:
"TypeError: value.charAt is not a function
In the example above, we are getting the error because we are using the ‘charAt()’ method on a datetype number.
To solve the “TypeError: charAt is not a function”, make sure to call the charAt() method on a data type string or convert the number to string before calling the charAt() method on it.
Here is an example:
const value = 234;
const result = value.toString().charAt(2);
console.log(result);
Output:
'4'
In the example above, we first converted the given value to a string using the toString() method, then we called a chartAt() method on it.
Note: The ‘charAt()’ method returns the character at a specified index in the given string.
Type checking
To avoid the run time errors, we can also check the given datatype is a string or not before calling the charAt() method on it.
Here is an example:
const value = 234;
if(typeof value === 'string'){
console.log(value.charAt(2));
}else{
console.log('Given value is not a string');
}
Conclusion
The “TypeError: charAt is not a function” error occurs, when we call a charAt() method on a value which is not string. To solve the error convert the value to an string before calling the charAt() method on it or make sure to use the charAt() method on valid strings.