ECMAScript Goodies_Minor _870x220

What are the best minor features of ES2017 and what's on the list for ES2018? This two-part series explores the latest and greatest features of ECMAScript. This part explores minor features like Object.values/Object.entries and string padding, where Part 1 covered major features.

Let's check in with ECMA International, Technical Committee 39! It turns out the 6 in ES6 does not stand for the number of years it takes for a release. I kid! Since ES6/ES2015 took so long to release (6 years, hence my jab) the committee decided to move to a yearly small-batch release instead. I'm a big fan of this and I think the momentum keeps things moving and JavaScript improving. What presents did we get for ES2017 and what's on our list for ES2018?

You can learn more about the TC39 process of proposals from 2ality by Dr. Axel Rauschmayer: The TC39 Process for ECMAScript Features.

ES2017

In January, at the TC39 meeting, the group settles on the ECMAScript proposals that would be slated as the features of ES2017 (also referred to ES8, which probably should be nixed to avoid confusion). This list included:

Major features

Minor features

In this post, the second in a two-part series, we'll cover the minor features listed above. You can read the first post to cover the major features.

Object.values/Object.entries

Proposed by: Jordan Harband

Object.values()

I have actually benefited from the useful addition of Object.values recently when pulling Philips Hue light information from an observable. It allowed me to iterate through my data's values because it returns an array of the object's properties.

// land before Object.values()
const lights = {{ id: 1, on: true, color: 'blue'}, { id: 2, on: false, color: 'red' }}
this.lights = Object.keys(data).map(key => data[key])

// the time is now aka WITH Object.values()
this.lights = Object.values(data)

// both return
// [{ id: 1, on: true, color: 'blue'}, { id: 2, on: false, color: 'red' }]

Fancy 💅, right?

Object.entries{}

This method takes what Object.values() does one step further. Looking at an object, a data structure of key-value pairs, each of those pairs is an entry. When you call Object.entries() it is returning an array containing an array for each of those entries.

Object.entries({ name: 'Toshmagosh', age:  12 })
// [[ "name", "Toshmagosh" ], [ "age", 12 ]]

It's really quite straightforward, but if you ever want to dive in more, JavaScript.info has a good rundown.

String Padding

Proposed by : Jordan Harband, Rick Waldron

I didn't think I was going to have to say this again but, left pad. Yes, the left pad debacle of 2016 raised the attention of the JavaScript community enough for TC39 to add string padding. To be fair though, it was about time for JavaScript to have some native methods to handle Strings. ✨ Welcome padStart/padEnd to the family, which currently was just a lonely String.prototype.trim (est. ES5)!

You are all smart people so you probably can surmise what each of these methods do. So, I'll just show you some examples instead of using my words.

// padStart adds padding until string reaches provided length
'puppies'.padStart(22)
// "puppies"

// or provide a filler instead of blank spaces
'nachos'.padStart(11, 'yum')
// "yumyunachos"

// padEnd works the same but adds to the end of the string
'Carlos Santana'.padEnd(30, '-^')
// "Carlos Santana-*--*--^*"

// Emoji trickiness
'🍞🥞🥚🌭'.padEnd(8)
// "🍞🥞🥚🌭" // no pad? yup, because the length === 8, emoji you so funny

To review this, both methods take an integer parameter that is telling them how long the final length of the string, including the padding, should be. If you pass a number shorter or equal to the original length of the string, nothing will change. Bravo, on wasting your time (just kidding 😁). You can also pass a string and padStart/padEnd will repeatedly add each item of that string to the start or end of the original string until the length matches the passed length parameter. As you can see in my example above, since I wanted a length of 11, padStart added ` 'yum' then the 'yu' and stopped. Emoji are very important so I wanted to remind you of their tricky string lengths, more information in this handy blog post.

Developers will, more than likely, take advantage of these methods which will also let them remove libraries they were using to accomplish string manipulation. There are more methods in the pipeline: trimStart/trimEnd is currently at stage 2 (out of the 4 stages, here's the process break down again 🙂👍). This will let us trim or remove starts and ends of strings. Fun fact: this proposal started out with trimLeft and trimRight but has been updated to trimStart and trimEnd to stay consistent with padStart and padEnd. Yay, consistency! It also helps with any confusion whether a language is read right-to-left or left-to-right.

Object.getOwnPropertyDescriptors()

Proposed by: Jordan Harband & Andrea Giammarchi

This is the plural version of Object.getOwnPropertyDescriptor which returns a descriptor of the property that's directly on an object, i.e. not on its prototype chain.

let popcorn = { action: 'pop', butter: true }
let popcornAction = Object.getOwnPropertyDescriptor(popcorn, 'action')

// popcornAction is {
//   value: "pop",
//   writable: true,
//   enumerable: true,
//   writable: true
// }

So, using the plural version you are able to capture all of an object's non-inherited (or own) property descriptors. Using the delicious example above:

let popcorn = { action: 'pop', butter: true }
let popcornProperties = Object.getOwnPropertyDescriptors(popcorn)

// popcornProperties is {
//   action: {
//     value: "pop",
//     writable: true,
//     enumerable: true,
//     writable: true
//   },
//   butter: {
//     value: true,
//     writable: true,
//     enumerable: true,
//     writable: true
//   }
// }

Why do we need these methods? Well the proposer, Jordan Harband, puts it well here:

There is not a single method in ECMAScript capable of simplifying a proper copy between two objects. In these days more than ever, where functional programming and immutable objects are essential parts of complex applications, every framework or library is implementing its own boilerplate in order to properly copy properties between composed objects or prototypes.

 — Jordan Harband

With this addition you can now use getPrototypeOf and getOwnPropertyDescriptors with objectCreate to copy object and easily give it the same prototype and property descriptors. Before, this was most often done using Object.assign, which would grab an object's properties and symbols instead of descriptors. That approach left the risk of discarding possible accessors.

// just to give you a bit of an idea
const toshmagosh = {
cuteLevel: 11,
breed: 'Blue Pomeranian',
treatTime: treat => {
console.log(Do you want a ${treat}?)
}
}

const newPuppy = Object.create(
Object.getPrototypeOf(toshmagosh),
Object.getOwnPropertyDescriptors(toshmagosh)
);

// newPuppy
// {cuteLevel: 11, breed: "Blue Pomeranian", treatTime: ƒ}

Appreciation Pause

Now, there are a lot of great people that are and have been on TC39, I would like to thank them all for their work. Doing this list has also put someone's name in writing multiple times: Jordan Harband. So, I just wanted to take a quick pause to 👏👏👏👏 Jordan, who is currently on a solid 1,325 day GitHub contributions streak as of December 1, 2017. Thanks for all you do for JavaScript, Jordan!!

Trailing Commas

Proposed by: Jeff Morrison

I must admit, I think trailing commas looks super sloppy and I have never been a big fan.

let why = [
'really?',
'must you?',
'yuck 😝',
]

That being said, I get it. I have had many occasions where I add an item to an array, a key value pair to an object, or delete an item and have had to remove or add a comma. I am one with the concept of minimizing how many keystrokes you must use. keysleft.com says I only have 213,407,968 and I just blew through 117 in this sentence alone! I've also heard the argument for the benefits this will add to checking your git diffs since you would only need to edit one line when adding function parameters, array items, etc. TBTH I'll probably take on this convention from now on. Okay, TC39? You win! 😘

What's to Come in 2018

There is an awesome, emoji-laden table of proposals and what stages they are in located here. You can also see the finished proposals including one that is already ready for 2018 publication!

Dr. Axel is here to keep you up-to-date with the happenings of ES2018: http://2ality.com/2017/02/ecmascript-2018.html.

Usually, at this point we're looking at Stage 4 proposals, which are proposals that will definitely be added in the next release, and Stage 3 proposals, which are proposals that have a good chance of being included in the next release.

So far, the stage 4-ers are:

  • Template Literal Revision proposed by Tim Disney. Currently, the escape sequence in template literals is problematic for embedding languages like domain-specific languages. This proposal will remove the restriction on escape sequences. To understand more click here 👆.

  • s (dotAll) flag for regular expressions by Mathias Bynens. This proposal is all about emoji!🎈 Okay, not entirely, but it introduces the /s flag into regular expressions to make up for the dot's (.) shortcomings (like not matching with non-BMP character such as emoji). There is more to it though, so check out Mathias's proposal.

The list of stage 3-ers is a bit longer so I will give you this helpful link to see the table and an image of it down below. How nice is that 😉.

stage 3 proposals

Read Part 1

As mentioned above, this is the second post in a two-part series. If you haven't seen the first part, that's where we covered the major features we listed earlier. You can check it out here.


Tara Manicsic
About the Author

Tara Z. Manicsic

Tara Z. Manicsic is a lifelong student, teacher, and maker. She has spent her career using JavaScript on both back-end and front-end to create applications. A Developer Advocate for Progress, Google Developer Expert, and international technical speaker, she focuses on conveying the codebase she has learned. She also works in her community launching & directing the Cincinnati Chapter of Women Who Code and the Cincinnati branch of NodeSchool.

Related Posts

Comments

Comments are disabled in preview mode.