Search⌘ K
AI Features

ES2017: String Padding, Object.entries(), and More

Understand key ES2017 JavaScript features including string padding for alignment, Object.entries and Object.values methods for object data access, property descriptors, trailing commas syntax, and shared memory with Atomics. Learn how these features improve coding practices and concurrency handling.

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.

Javascript (babel-node)
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:

Javascript (babel-node)
console.log("hi".padStart(10));
// 10 - 2 = 8 empty spaces
// " hi"
console.log("welcome".padStart(10));
// 10 - 6 = 4 empty spaces
// " welcome"

 

Right align with padStart #

We can use padStart if we want to right align something.

Javascript (babel-node)
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 them perfectly aligned to the right.

  ...