Destructuring (destructured) parameters in ES6/ES2015
Since I’ve been coding ruby a lot the last couple of years I’m used to defaults in keyword arguments since ruby 2.0. In Javascript this is kinda equal to the use of destructured parameters like this:
const test = ({ param = 'default value' } = {}) => param;
So when running this I’m getting the default value:
test() // 'default value'
But as I’m coming from ruby, that = {}
is very easy to forget which doesn’t
set the default value:
const test = ({ param = 'default value' }) => param;
test() // TypeError: (destructured parameter) is undefined
When you think about how the destructured parameters work, and realize that the object in the parameters are just a parameter and needs a default value; it make sense. But if you’re just glancing at it quickly, especially coming from ruby it doesn’t really make sense.
Learning
- Don’t take stuff for granted
JS !== Ruby
References
- https://www.smashingmagazine.com/2016/07/how-to-use-arguments-and-parameters-in-ecmascript-6/#destructuring
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/default_parameters#Destructured_parameter_with_default_value_assignment
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment