let text, value;
if (typeof f == 'string') {
text = value = f;
} else {
let {
text, value
} = f;
}
Doing this creates two new vars (from the else
), however if I write it like so:
let text, value;
if (typeof f == 'string') {
text = value = f;
} else {
{
text, value
} = f;
}
I receive a syntax error. What is the best approach here?
You need parens around the assignment:
let text, value;
if (typeof f == 'string') {
text = value = f;
} else {
({ // ( at start
text, value
} = f); // ) at end
}
(Live copy on Babel.)
You need those parens for the same reason you need parens or similar to immediately invoke a function: To tell the parser that it should expect an expression, not a statement. Without the parens, when it encounters the {
, it thinks that's the beginning of a block. But unlike with the function, it has to 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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With