Solve - padStart is not a function Error in JavaScript

avatar

Borislav Hadzhiev

Wed Oct 20 20212 min read

banner

Photo by Luigi Manga

Solve - padStart is not a function Error #

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

typeerror padstart is not a function

Here is an example of how the error occurs.

index.js
const num = 123; // โ›”๏ธ TypeError: padStart is not a function const result = num.padStart(5, '0');

We called the String.padStart method on an object and got the error back.

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

index.js
const num = 123; // โ›”๏ธ TypeError: padStart is not a function const result = num.toString().padStart(5, '0'); console.log(result); // ๐Ÿ‘‰๏ธ "00123"

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

index.js
const str = null; const result = typeof str === 'string' ? str.padStart(5, '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 padStart method on it, otherwise we return an empty string to be consistent.

If you want to use the padStart method on all of the strings in an array, you can use the map method to iterate over the array and call the padStart method on each string.

index.js
const arr = ['A', 'B', 'C']; const result = arr.map(str => str.padStart(2, '_')); // ๐Ÿ‘‡๏ธ ['_A', '_B', '_C'] console.log(result);
The map method takes a function and calls the function on each element in the array. On each iteration, we call the padStart method to pad each letter with an underscore.

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

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee