I was wondering why we can't use Logical assignment operators with object destructuring.
Example...
const { prop &&= 1 } = object; // Sets prop to 1, if it is truthy.
const { prop ||= 1 } = object; // Sets prop to 1, if it is falsey.
const { prop ??= 1 } = object; // Sets prop to 1, if it is a null.
Let me know what you think. Thank you .
My guess is that's to maintain consistency with other augmented assignment operators, none of which work in destructuring.
1 Like
Linking other thread where this was also asked
Logical assignment for default assignments
2 Likes
The first “=
” sign in const { prop = 1 } = object
(or in function foo(arg = 1) { }
) is not an assignment operator; rather it specifies a default value. Therefore, any extension of the assignment operator (“compound assignment” or “logical assignment”) does not apply.
Of course, it is possible to make sense of const { prop ||= 1 } = object
. However, I’m wondering whether the cost of adding yet another complexity in the language is worth the gain in conciseness? For comparison, as of today, you can write:
let { prop } = object;
prop ||= 1;
2 Likes