I'm using destructuring to declare some variables like this:
const { a, b, c } = require('./something'),
{ e = 'default', f = 'default'} = c;
Is there a way to make this into single line? I've tried something like :
const { a, b, c = { e = 'default', f = 'default'} } = require('./something');
But it gives me an error:
SyntaxError: Invalid shorthand property initializer
Gotchas of Nested DestructuringOne thing we cannot do with nested destructuring is to destructure a null or undefined value. If we attempt to do so it will throw an error: So, if we want to use nested destructuring we must be certain that the nested structure exists, or intentionally catch the thrown error.
Each destructured property can have a default value. The default value is used when the property is not present, or has value undefined . It is not used if the property has value null . The default value can be any expression.
It's common for objects to contain nested objects and arrays. Destructuring allows us to extract properties that are nested in objects using the syntax that we learned above for destructuring arrays and objects.
The above code will not work if the object does not have c in it
const { a, b, c: { e = 'default', f = 'default'}} = {a: 1, b: 2}
console.log(`a: ${a}, b: ${b}, e: ${e}, f: ${f}`)
const { a, b, c: { e = 'default', f = 'default'} ={} } = {a: 1, b: 2}
console.log(`a: ${a}, b: ${b}, e: ${e}, f: ${f}`)
Just replace =
with :
:
const {a, b, c: {e = 'default', f = 'default'}} = require('./something')
Demo:
const { a, b, c: { e = 'default', f = 'default'} } = {a: 1, b: 2, c: {e: 3}}
console.log(`a: ${a}, b: ${b}, e: ${e}, f: ${f}`)
It prints:
a: 1, b: 2, e: 3, f: default
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