ES2017: String Padding, Object.entries(), and More
Let's discover the many new and interesting features that ES2017 brought.
ES2017 introduced many cool new features, which we’ll check out below.
String padding (.padStart()
and .padEnd()
) #
We can now add some padding to our strings, either at the end (.padEnd()
) or at the beginning (.padStart()
) of them.
Press + to interact
console.log("hello".padStart(6));// " hello"console.log("hello".padEnd(6));// "hello "
We specified that we want 6 as our padding, so then why in both cases did we only get 1 space?
It happened because padStart
and padEnd
will go and fill the empty spaces. In our example “hello” is 5 letters, and our padding is 6, which leaves only 1 empty space.
Look at this example:
Press + to interact
console.log("hi".padStart(10));// 10 - 2 = 8 empty spaces// " hi"console.log("welcome".padStart(10));// 10 - 6 = 4 empty spaces// " welcome"
Press + to interact
const strings = ["short", "medium length", "very long string"];const longestString = strings.sort(str => str.length).map(str => str.length)[strings.length -1];strings.forEach(str => console.log(str.padStart(longestString)));// very long string// medium length// short
First we grabbed the longest of our strings and measured its length. We then applied a padStart
to all the strings based on the length of the longest so that we now have all of ...
Access this course and 1400+ top-rated courses and projects.