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
    Responsive and Infinitely Scalable JS Animations

    Back in late 2012 it was not easy to find open source projects using requestAnimationFrame() - this is the hook that allows Javascript code to synchronize with a web browser's native paint loop. Animations using this method can run at 60 fps and deliver fantastic...

  • By
    Welcome to My New Office

    My first professional web development was at a small print shop where I sat in a windowless cubical all day. I suffered that boxed in environment for almost five years before I was able to find a remote job where I worked from home. The first...

Incredible Demos

  • By
    Introducing MooTools ScrollSide

    This post is a proof of concept post -- the functionality is yet to be perfected. Picture this: you've found yourself on a website that uses horizontal scrolling instead of vertical scrolling. It's an artistic site so you accept that the site scrolls left to right.

  • By
    Chris Coyier’s Favorite CodePen Demos II

    Hey everyone! Before we get started, I just want to say it's damn hard to pick this few favorites on CodePen. Not because, as a co-founder of CodePen, I feel like a dad picking which kid he likes best (RUDE). But because there is just so...

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.

    • Tyler Graf

      No way, it’s perfection. :)

    • Allan Bonadio

      But, if you’ve ever written code to generate JSON, you’ll see that getting rid of that last comma is a pain in the butt. It’s so much simpler if the lines are consistent; each line done with a print statement with a comma, done.

      And, even in hand coding, how many syntax errors do you get when you rearrange the items in an array or object? eg

      {
        name: 'Joe Schmoe',
        phone: '123-456-7890'
        level: 3,
      }
      
  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.

  4. Kailash

    Trailing comma feature was not required for the developer. Please don’t implement the features like this to confuse the developers.

  5. steve

    I agree with Hlk. I bet a large percentage of people landing on this page, are searching for job interview prep reasons, and we want to rattle off to the employer the answer to: “what es7 features have you used? and es8? “. etc.. but thanks for the info

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