Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 destructuring assignment with more than one variable type

I have a function that returns 5 objects, and I would like to declare 4 of them using const and 1 of them using let. If I wanted all objects declared using const I could do:

const { thing1, thing2, thing3, thing4, thing5 } = yield getResults();

My current workaround is:

const results = yield getResults();

const thing1 = results.thing1;
const thing2 = results.thing2;
const thing3 = results.thing3;
const thing4 = results.thing4;

let thing5 = results.thing5; 

But I'm wondering if destructuring assignment allows you to do this more elegantly.

No mention of this question on MDN or on stackoverflow, as far as I can see.

like image 246
the holla Avatar asked Jun 20 '16 22:06

the holla


2 Answers

It isn't possible to perform a destructure that initialises both let and const variables simultaneously. However the assignments to const can be reduced to another destructure:

const results = yield getResults()

const { thing1, thing2, thing3, thing4 } = results

let thing5 = results.thing5
like image 108
sdgluck Avatar answered Nov 15 '22 02:11

sdgluck


You still can use destructuring separately:

const results = yield getResults();
const { thing1, thing2, thing3, thing4} = results;
let   { thing5 } = results;

Alternatively, it is possible to do

let thing5;
const { thing1, thing2, thing3, thing4 } = { thing5 } = yield getResults();

but I guess that should rather be avoided to reduce the WTF/minute of your code.

like image 35
Bergi Avatar answered Nov 15 '22 03:11

Bergi