4 ms·
I've been writing ES6 with Babel for a couple of months now, and I've fallen in love with destructuring - it's my second favorite part, besides arrow functions.
by dandelany 11y ago
I've been writing ES6 with Babel for a couple of months now, and I've fallen in love with destructuring - it's my second favorite part, besides arrow functions. My only complaint, having run into this a few times in real code, is that you can only use destructuring with assignment, not with existing variables. So this works:
let myThing = {a: 4};
let {a} = myThing;
But this does not:
let a = 5;
let myThing = {a: 4};
{a} = 5;
I understand there are some problems of ambiguity here, but it seems to me this could be made to work somehow?
- loganfsmyth 11y agoYeah, I wish that were handled better too. Since the parser is expecting a statements, it parses it like { a } = 5 As in, a block with just an "a" in it, followed by an assignment to nothing, which throws an syntax error. You can however do ({a} = 5); to make the parser switch to expecting a destructuring pattern instead of an block statement.
- dandelany 11y agoWhoops, my last line contains a major typo and should read `{a} = myThing;`. And you've dutifully carried over my typo to your example :D But regardless, the corrected version of your example: `let a; ({a} = {a:5});` works like a charm and is very handy! Thanks for the tip!
- deleted 11y ago[deleted]
- lucian1900 11y agoAt least with let you can reliably shadow the previous binding, which in most cases will be equivalent.