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