Learn JavaScript ES 2017: String padding — padStart & padEnd
ES 2017 introduces padStart and padEnd. Learn how to use them in less than three minutes in this JS Quickie

String Padding
The padStart()
& padEnd()
methods pad a string with another string until the resulting string reaches the supplied length. The string will repeat as necessary.
padStart()
— padding is applied to the left (beginning) side of the string.padEnd()
— padding is applied to the right (ending) side of the string.
padStart
Let’s look at a simple example. Below, we’ll be working with the string 'cat'
. Only one parameter is required — the length of the resulting string. As you’ll see, we can optionally provide a second variable — the string to pad with:
'cat'.padStart(5); // ' cat'
'cat'.padStart(5, 'a'); // 'aacat'
Below are some advanced use cases. Note that if the string is initially longer than the padStart()
length, nothing is appended to the string:
'cat'.padStart(1, 'a'); // 'cat'
'cat'.padStart(5, 'abc'); // 'abcat'
'cat'.padStart(8, 'abc'); // 'abcabcat'
padEnd
Again, the only difference here is that the string is applied to end of our current string. We’ll use the same examples as above:
'cat'.padEnd(5); // 'cat '
'cat'.padEnd(5, 'a'); // 'cataa'
Similarly, our advanced examples:
'cat'.padEnd(1, 'a'); // 'cat'
'cat'.padEnd(5, 'abc'); // 'catab'
'cat'.padEnd(8, 'abc'); // 'catabcab'
Use Cases
Here’s one possible use case for String Padding: Aligning console output. Consider the following code:
We have an object with city names and corresponding high/low temperatures. The object is mapped over using ES 2017’s object.entries()
. Read more about object.entries()
here. The resulting values are logged to the conosle:
City: Portland Weather: 78/50
City: Dublin Weather: 88/52
City: Lima Weather: 58/40
That’s annoying to read. Everything overlaps. By adding padEnd()
to our code, we can drastically increase readability. Here’s the new code:
By using padEnd()
we can ensure each log is aligned, creating a much nicer table layout:
City: Portland Weather: 78/50
City: Dublin Weather: 88/52
City: Lima Weather: 58/40
Want more advanced JavaScript?
Check out A Beginners Guide to Advanced JavaScript
Closing Notes
Thanks for reading. I’m doing a whole series on JavaScript ES 2017. Please consider entering your email here if you’d like to be added to my once-weekly email list.
If advanced JavaScript tutorials like this interest you and you want to learn more, check out JavaScript: Understanding the Weird Parts.