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
    9 Mind-Blowing WebGL Demos

    As much as developers now loathe Flash, we're still playing a bit of catch up to natively duplicate the animation capabilities that Adobe's old technology provided us.  Of course we have canvas, an awesome technology, one which I highlighted 9 mind-blowing demos.  Another technology available...

  • By
    Vibration API

    Many of the new APIs provided to us by browser vendors are more targeted toward the mobile user than the desktop user.  One of those simple APIs the Vibration API.  The Vibration API allows developers to direct the device, using JavaScript, to vibrate in...

Incredible Demos

  • By
    9 Mind-Blowing Canvas Demos

    The <canvas> element has been a revelation for the visual experts among our ranks.  Canvas provides the means for incredible and efficient animations with the added bonus of no Flash; these developers can flash their awesome JavaScript skills instead.  Here are nine unbelievable canvas demos that...

  • By
    Style Textarea Resizers

    Modern browsers are nice in that they allow you to style some odd properties.  Heck, one of the most popular posts on this blog is HTML5 Placeholder Styling with CSS, a tiny but useful task.  Did you know you can also restyle the textarea resizer in WebKit...

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.

    • I think it depends on your code style.

      For small, inline objects/arrays, it doesn’t make sense, but for large, multi-line objects or arrays it’s extremely useful.

      We’ve been using them in PHP for years, and it makes such a difference.

  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 :-)

    • Igor Fastovski

      Template literals and default parameters are cool but I think they are from ES6.

  3. Hlk

    Cool features!

    But It would be better if you also denoted which of those features are ES7 and which are ES8. Thanks for sharing anyway.

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