Solve - charAt is not a function Error in JavaScript

avatar

Borislav Hadzhiev

Last updated: Oct 20, 2021

banner

Check out my new book

Solve - charAt is not a function Error #

The "charAt is not a function" error occurs when we call the charAt() 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 charAt method on strings.

typeerror charat is not a function

Here is an example of how the error occurs.

index.js
const num = 9876; // ⛔️ TypeError: charAt is not a function const result = num.charAt(0);

We called the String.charAt method on a number and got the error back.

To solve the error, make sure to only call the charAt() method on strings. You can convert most values to a string by using the toString() method.

index.js
const num = 9876; const result = num.toString().charAt(0); console.log(result); // 👉️ "9"

Alternatively, you can check if the value is a string before calling the charAt() method.

index.js
const str = null; const result = typeof str === 'string' ? str.charAt(0) : ''; console.log(result); // 👉️ ""

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 charAt method on it, otherwise we return an empty string to be consistent.

If you have an array of strings, you probably want to join the array into a single string before calling the charAt method.

index.js
const arr = ['hello', 'world']; const result = arr.join(' ').charAt(0); console.log(result); // 👉️ "h"
The join() method allows us to join an array into a string where the substrings are separated by a provided separator. We can then call the charAt method on the string and get the character at the specific index.

If the error persists, console.log the value you're calling the charAt 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 charAt() method.

Further Reading #

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