Destruction ES6, dynamic assignment

let text, value; if (typeof f == 'string') { text = value = f; } else { let { text, value } = f; } 

Doing this creates two new vars (from else ), however, if I write it like this:

 let text, value; if (typeof f == 'string') { text = value = f; } else { { text, value } = f; } 

I get a syntax error. What is the best approach here?

+6
source share
1 answer

You need the guys around the quest:

 let text, value; if (typeof f == 'string') { text = value = f; } else { ({ // ( at start text, value } = f); // ) at end } 

( Live copy on Babel .)

You need these parens for the same reason you need partners or similar functions to call the function immediately : To tell the parser that it should expect an expression, not an assertion, Without parens, when it encounters { , it thinks the beginning of the block. But unlike a function, it should be parens, not a leading unary + ,! etc. like this :

 let text, value; if (typeof f == 'string') { text = value = f; } else { +{ // <== Doesn't work like it does with IIFEs text, value } = f; } 
+7
source

Source: https://habr.com/ru/post/989097/


All Articles