Kent C. Dodds News

Subscribe
Archives
June 11, 2018

JavaScript default parameters

Today I thought I’d take you through one of the examples from my es6 workshop.

Consider the following code:

function getCandy(kind, size, upperKind, callback) {
  if (!kind) {
    requiredPram('kind')
  }
  if (!size) {
    requiredPram('size')
  }
  upperKind = upperKind || kind.toUpperCase()
  callback = callback || function noop() {}

  const result = {kind, size, upperKind}
  callback(result)
  return result
}

function requiredParam(argName) {
  throw new Error(`${argName} is required`)
}

It’s fairly simple, but there are potential bugs (read about Falsy on MDN) and some annoying boilerplate. Luckily for us, ES6 introduced new syntax into JavaScript that we can use to simplify things a bit. In particular: default parameters. Let’s checkout what the above would be like when using this feature.

function getCandy(
  kind = requiredParam('kind'),
  size = requiredParam('size'),
  upperKind = kind.toUpperCase(),
  callback = function noop() {},
) {
  const result = {kind, size, upperKind}
  callback(result)
  return result
}

function requiredParam(argName) {
  throw new Error(`${argName} is required`)
}

Notice that we’re able to take each expression and put it on the right side of the equals sign. If the parameter is undefined then the expression on the right side will be evaluated. This allows us to only call the requiredParam function if kind or size is undefined. It also is possible to use the value of other parameters in our expression like we do in the default param for upperKind which I find to be a ridiculously cool feature and I use this all the time in options configuration for some of my tools (for example).

I’ll add that the same kinds of semantics would apply for object destructuring (whether as a parameter or not) as well. For example, if we change the arguments to be an options object:

function getCandy(options = {}) {
  const {
    kind = requiredParam('kind'),
    size = requiredParam('size'),
    upperKind = kind.toUpperCase(),
    callback = function noop() {},
  } = options
  // etc...
}

Or, if we want to destructure the options object directly in the parameter list:

function getCandy({
  kind = requiredParam('kind'),
  size = requiredParam('size'),
  upperKind = kind.toUpperCase(),
  callback = function noop() {},
} = {}) {
  // etc...
}

Fun stuff!

Conclusion

I hope you find this helpful! If you’d like to watch me talk about this a bit, you can check out this section of my ES6 workshop I gave and recorded at PayPal a while back: ES6 and Beyond Workshop Part 1 at PayPal (Jan 2017). Good luck!

Looking for a job? Looking for a developer? Check out my job board: kcd.im/jobs

  • JavaScript Developer (Remote)
  • Software Engineer (front end) (Portland, OR)

Learn more about JavaScript from me:

  • More than you want to know about ES6 Modules @ Learn to Code Websites and Apps Meetup (remote)
  • ES6 and Beyond Workshop Part 1 at PayPal (Jan 2017)
  • ES6 and Beyond Workshop Part 2 at PayPal (March 2017)
  • Code Transformation and Linting
  • Writing custom Babel and ESLint plugins with ASTs

Also, don’t forget to subscribe to my youtube channel for my daily devtips, like the one today where I demo some advanced features of destructuring!

Things to not miss:

  • Semver Calc - A sweet new app by Tarang Hirani and Shriram Balaji. It allows you to try out semver ranges on packages versions to fine-tune the version range. Especially useful for peerDependencies.
  • AnxietyTech - A conference on July 18th, 2018 to bring awareness of mental health issues in tech. Use code TECH for $25 off.
  • Refined Twitter - Browser extension that simplifies the Twitter interface and adds useful features. I love it.

Some tweets from this last week:

> See you all in a week šŸŒ²šŸŒ²šŸŒ²šŸŒ²šŸŒ²šŸŒ²šŸŒ²šŸŒ²šŸŒ²šŸ—»šŸŒ²šŸŒ²šŸŒ²šŸŒ²šŸŒ²šŸŒ² – 2 Jun 2018

Mountain view

> When you have an hour to speak but only ~30 minutes of speaking material… > > I’m pretty sure nobody ever complained about a talk NOT lasting a full hour. – 8 Jun 2018

> With the react team making the react docs really awesome and comprehensive, maybe there’s a need for a site that’s more terse šŸ¤” maybe such a site exists…? – 10 Jun 2018

This week’s blog post is “When to use Control Props or State Reducers”. It’s the published version of my newsletter from 2 weeks ago. If you thought it was good, go ahead and give it some claps (šŸ‘x50) and a retweet:

screenshot of the tweet

Special thanks to my sponsor Patreons: Hashnode

P.S. If you like this, make sure to subscribe, follow me on twitter, buy me lunch, support me on patreon, and share this with your friends šŸ˜€


šŸ‘‹ Hi! I’m Kent C. Dodds. I work at PayPal as a full stack JavaScript engineer. I represent PayPal on the TC39. I’m actively involved in the open source community. I’m an instructor on egghead.io, Frontend Masters, and Workshop.me. I’m also a Google Developer Expert. I’m happily married and the father of four kids. I like my family, code, JavaScript, and React.

Don't miss what's next. Subscribe to Kent C. Dodds News:
This email brought to you by Buttondown, the easiest way to start and grow your newsletter.