I use ES6 features with babel compiler. I have a function which takes option object as an argument:
function myFunction({ option1 = true, option2 = 'whatever' }) {
console.log(option1, option2);
// do something...
}
When I call it, destructuring happens and everything works well. I want to call it with default options most of the time, so I do:
myFunction({}); // true 'whatever'
but it looks little bit strange. It would much more cleaner just call:
myFunction(); // TypeError: Cannot read property 'option1' of undefined
Is it possible?
Default value It is not used if the property has value null . The default value can be any expression. It will only be evaluated when necessary. const { b = console.log("hey") } = { b: 2 }; // Does not log anything, because `b` is defined and there's no need // to evaluate the default value.
When destructuring the objects, we use keys as the name of the variable. The variable name must match the property (or keys) name of the object. If it does not match, then it receives an undefined value. This is how JavaScript knows which property of the object we want to assign.
Destructuring is a JavaScript expression that allows us to extract data from arrays, objects, and maps and set them into new, distinct variables. Destructuring allows us to extract multiple properties, or items, from an array at a time.
To destructure an array in JavaScript, we use the square brackets [] to store the variable name which will be assigned to the name of the array storing the element. const [var1, var2, ...]
Yes, you just have to provide a default value for the complete argument:
function myFunction({option1 = true, option2 = 'whatever'} = {}) {
// ^^^^
console.log(option1, option2);
// do something...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With