Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 destructuring, dynamic assignment [duplicate]

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?

like image 449
benhowdle89 Avatar asked Jun 14 '15 17:06

benhowdle89


1 Answers

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;
}
like image 131
T.J. Crowder Avatar answered Oct 23 '22 07:10

T.J. Crowder