Six Tiny But Awesome ES7 + ES8 Features

By  on  

Development of new features for the core JavaScript language has really improved over the last five years, thanks in part to JavaScript frameworks pushing the limits and proving how important given functionality can be.  My previous ES6 posts, Six Tiny But Awesome ES6 Features and Six More Tiny But Awesome ES6 Features, highlighted a dozen excellent features that were added to JavaScript to make our lives easier -- and they certainly do.  Let's have a look at some of the "small" functionality that ES7 and ES8 brought us!

String.prototype.padStart/padEnd

padStart and padEnd allow us to pad a given string with any text of our choosing to ensure a string matches a given length:

// padStart(desiredLength, textToPrepend)

// No text
''.padStart(10, 'Hi') // 'HiHiHiHiHi'

// Some text
'def'.padStart(6, 'abc') // 'abcdef'

// Only use what gets to length
'5678'.padStart(7, '1234') // '1235678'

// padEnd(desiredLength, textToAppend)

'23'.padEnd(8, '0') // '23000000'

One usage of padStart could include prepending an area code to phone number if the user input isn't the correct length.  padEnd could be used for decimal precision.

Object.entries

Object.entries allows us to get an object's enumerable property pairs in array format ([key, value]):

// Object literal
Object.entries({ 'a': 'A', 'b': 'B' }); // [["a","A"],["b","B"]]

// String
Object.entries('david') // [["0","d"],["1","a"],["2","v"],["3","i"],["4","d"]]

Object.entries follows the same order as for...in would.

Object.values

Object.keys has been immensely useful for me so I was also excited to see Object.values introduced:

// Object literal
Object.values({ 'a': 23, 'b': 19 }) // [23, 19]

// Array-like object (order not preserved)
Object.values({ 80: 'eighty', 0: 1, 1: 'yes' }) // [1, 'yes', 'eighty']

// String
Object.values('davidwalsh') // ["d", "a", "v", "i", "d", "w", "a", "l", "s", "h"]

// Array
Object.values([1, 2, 3]) // [1, 2, 3]

Object.values provides value entries in object literals, arrays, strings, etc.

Array.prototype.includes

Array.prototype.includes is a bit like indexOf but instead returns a true or false value instead of the item's index:

['a', 'b', 'c'].includes('a') // true, not 0 like indexOf would give
['a', 'b', 'c'].includes('d') // false

indexOf has been used over the years to detect item presence in array, but the `0` index can lead to false negatives if not coded properly.  I'm glad JavaScript has added a function that returns exactly what we need: a positive or negative answer!

Exponentiation

JavaScript has introduced a shorthand method of exponentiation:

// 2 to the power of 8
Math.pow(2, 8) // 256

// ..becomes
2 ** 8 // 256

This new syntax accomplishes the same as  Math.pow with less code!

Trailing Commas

I'm old enough to remember the days where a trailing comma would completely explode your JavaScript code in Internet Explorer 6.  JavaScript now accommodates for the extra comma:

let myObj = { a:'b', b: 'c', } // No error!

let myArr = [1, 2, 3, ] // No error!

[1, 2, 3,].length // 3
[1, 2, 3, , , ].length // 5

The case of the Array length is one to keep in mind.  ESLint has a comma-dangle rule you can use to ensure your comma dangle usage is consistent.

Bonus:  async / await

Obviously async and await, the new method of handling async tasks, is no "tiny" addition, but it certainly is awesome!  Read my async and await guide to transform your callback hell into a more elegant, top-down approach to async code!

With every iteration of JavaScript we're solving problems that we'd been having with lack of functionality or bastardized usage of other functions.  What's your favorite recent addition to JavaScript?

Recent Features

  • By
    LightFace:  Facebook Lightbox for MooTools

    One of the web components I've always loved has been Facebook's modal dialog.  This "lightbox" isn't like others:  no dark overlay, no obnoxious animating to size, and it doesn't try to do "too much."  With Facebook's dialog in mind, I've created LightFace:  a Facebook lightbox...

  • By
    How to Create a Twitter Card

    One of my favorite social APIs was the Open Graph API adopted by Facebook.  Adding just a few META tags to each page allowed links to my article to be styled and presented the way I wanted them to, giving me a bit of control...

Incredible Demos

  • By
    Create a Trailing Mouse Cursor Effect Using MooTools

    Remember the old days of DHTML and effects that were an achievement to create but had absolutely no value? Well, a trailing mouse cursor script is sorta like that. And I'm sorta the type of guy that creates effects just because I can.

  • By
    Cross Browser CSS Box Shadows

    Box shadows have been used on the web for quite a while, but they weren't created with CSS -- we needed to utilize some Photoshop game to create them.  For someone with no design talent, a.k.a me, the need to use Photoshop sucked.  Just because we...

Discussion

  1. Mike Collins

    In my mind Trailing Commas isn’t a feature. It is a poor way of allowing developers to be sloppy.

    • It was mainly proposed for version control diffs:

      Without trailing commas:

      let opts = {
      - foo: 'bar'
      + foo: 'bar',
      + baz: 'new'
      }
      

      With trailing commas:

      let opts = {
        foo: 'bar',
      + baz: 'new',
      }
      

      For multiline objects/array, I personally think it looks a lot better.

    • Jonathon Nordquist

      Gotta agree with Mike on this, gaining a minor improvement in source control isn’t worth giving an out for poorly written code. Especially as a trailing comma like this is likely to cause confusion. If I open a file and see that I’m going to be wondering what the authors intent was, and if there is something should be missing. Hopefully this is dropped from the spec.

    • Jonathon Nordquist

      Oh, and I should also add, excellent article. First time to your site and I’ll be checking out more of your writing in the future.

  2. How about template strings for multi line and inline variable parsing:

    let what = 'great'
    
    let statement = `
    Multi line
    
    is  ${what}!
    `
    

    Or, default parameters for functions:

    let add = (x = 0, y = 0) => x + y
    

    I think those are smallish enough to add to this list :-)

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!