Why you should be destructuring your method parameters in ES6

Published April 02, 2020, 1 min read, tagged as: javascriptcodequick tip

A lot of times when we're defining methods and creating classes, we use "config objects" to group parameters in a neat way so that we don't have long, hard to maintain method calls. Config objects are also an awesome way to create optional parameters or set default values.

Pre ES6, we would do this all manually like this:

function newPet(config) {
  var type = config.type || 'cat'
  var name = config.name || 'Snoopy'
  var color = config.color || 'black'

  // ...
}

newPet({type: 'dog', name: 'Dexter', color: 'brown'})

Aside from the benefits, what this pattern doesn't give us is an idea of what parameters an object expects at a quick glance. Also it doesn't play nice with VSCode autocomplete because there's no definition. ES6 gives us the ability to neatly define these parameters in a cleaner way, set default values and even make the whole object optional.

ES6 destructuring:

function newPet({type: 'cat', name: 'Snoopy', color: 'black'}) {
  // ...
}

Optional config:

function newPet({type: 'cat', name: 'Snoopy', color: 'black'} = {}) {
  // ..
}

I tweet about this type of thing a lot. If you enjoyed this article, you may enjoy following me.

April 13, 2020, 1 min read
javascriptcodequick tip

Quick JavaScript Tip: Storing unique data using Sets

Quick JavaScript Tip: Sets in JavaScript are a great way to store unique values. You can even convert Arrays to Sets to deduplicate them.

Read more

World Class Teams Create World Class Products

A Guide for Tech Leaders Navigating Growth and Change.

I'm writing a book! I share:

  • My framework to define and achieve engineering goals so you can move the needle in your organization and keep everyone rowing in the same direction
  • How to retain top tech talent and build high-performing teams
  • How to release great products rapidly with a structured Software Development Lifecycle (SDLC)
  • How to manage yourself and avoid common pitfalls that challenge many leaders
  • How to manage multiple teams and learn how to manage managers
  • Proven tactics to deliver better customer experience every time, even in fast paced environments

Released September 30, 2020

Subscribe to the mailing list to stay up to date

© 2020 Hashtag Coder
Built with Gatsby