JavaScript: padStart() and padEnd()

·

2 min read

padStart() and padEnd() are really useful for getting your string to be a certain length. I've found more of a use for them for numbers (converted to strings).

Let's say you have to write all numbers as two digits, even if they are 0-9. To do this we can break out the trusty for loop:

let number = 1;
if (number < 10 ) {
  number = '0' + number;
}

Simple, right? But what if you can do the same thing without even having to check if your number isn't two digits to start with:

let number = 1;
number = number.toString().padStart(2, '0');

The beauty of this code is that if your number is 10 it will return 10, not 010. You don't need the condition because you're telling it you want your 'number' to be two digits long. If it already is, it does nothing.

padEnd() does the same thing, but at the end of a string instead.