destructuring assignment doesn't work for the field in one object holds a falsy value, as follow:
let { aaa = 123 } = { aaa: null }
console.log(aaa) // null
so, how to achive ||=
in object destructuring assignment to implement such the field's destructed defalut value? like this:
let { aaa ||= 123 } = { aaa: null }
console.log(aaa) // 123
// it equals to
// let aaa = ({ aaa: null }).aaa || 123
So you cannot do what you are trying to do.
The destructuring assignment works as expected/specified. It is just that the default value only works when the destructured value is undefined
.
You have to use the normal syntax for "falsy" values ( note : this includes undefined, false, 0, NaN
etc. Extensive list at https://developer.mozilla.org/en-US/docs/Glossary/Falsy ).
let { aaa } = { aaa: null }
aaa ||= 123;
Quoting from MDN Destructuring assignment
for objects
Default values
A variable can be assigned a default, in the case that the value unpacked from the object isundefined
.
for arrays
Default values
A variable can be assigned a default, in the case that the value unpacked from the array isundefined
.
You can add a default value in this way
let obj = null
{ obj1 } = { obj1: obj || 123 }
OR
try assigning values to an object using a constructor. In that way the destructuring would work fine:
class Obj1 {
a: string
b: number
constructor(obj) {
this.a = obj && obj.a || 'default a'
this.b = obj && obj.b || 1
}
}
let obj = null
let obj1 = new Obj1(obj)
let {aaa} = {aaa: obj1}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.