JavaScript default parameters

Photo by Jude Beck on Unsplash

The expressive power of expressions in default values for parameters

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

Consider the following code:

1 function getCandy ( kind , size , upperKind , callback ) { 2 if ( ! kind ) { 3 requiredParam ( 'kind' ) 4 } 5 if ( ! size ) { 6 requiredParam ( 'size' ) 7 } 8 upperKind = upperKind || kind . toUpperCase ( ) 9 callback = callback || function noop ( ) { } 10 11 const result = { kind , size , upperKind } 12 callback ( result ) 13 return result 14 } 15 16 function requiredParam ( argName ) { 17 throw new Error ( ` ${ argName } is required ` ) 18 }

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.

1 function getCandy ( 2 kind = requiredParam ( 'kind' ) , 3 size = requiredParam ( 'size' ) , 4 upperKind = kind . toUpperCase ( ) , 5 callback = function noop ( ) { } , 6 ) { 7 const result = { kind , size , upperKind } 8 callback ( result ) 9 return result 10 } 11 12 function requiredParam ( argName ) { 13 throw new Error ( ` ${ argName } is required ` ) 14 }

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:

1 function getCandy ( options = { } ) { 2 const { 3 kind = requiredParam ( 'kind' ) , 4 size = requiredParam ( 'size' ) , 5 upperKind = kind . toUpperCase ( ) , 6 callback = function noop ( ) { } , 7 } = options 8 9 }

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

1 function getCandy ( { 2 kind = requiredParam ( 'kind' ) , 3 size = requiredParam ( 'size' ) , 4 upperKind = kind . toUpperCase ( ) , 5 callback = function noop ( ) { } , 6 } = { } ) { 7 8 }

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!