6
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?

benhowdle89
  • 34,076
  • 63
  • 192
  • 314

1 Answers1

7

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;
}
Community
  • 1
  • 1
T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639
  • Good answer. Minor note: The parentheses only need to surround the curly braces; the assignment itself can be outside. – Zirak Jun 14 '15 at 18:38
  • @Zirak: No, the parens need to be around the *whole* assignment expression; it's an error otherwise: [bit.ly link to Babel repl (too long to paste in a comment)](http://bit.ly/1HGPapN). They even have a specific message for it: "You're trying to assign to a parenthesized expression, eg. instead of `({a}) = 0` use `({a} = 0)`" And if you think about it, that's not at all surprising: With the parens only around the `{}`, it looks like an object initializer in parens (because in ES6 you can use that shorthand form). – T.J. Crowder Jun 14 '15 at 19:10
  • 1
    Didn't know Babel. thanks. – Royi Namir Jun 14 '15 at 19:32
  • @RoyiNamir: :-) It's not immediately obvious from the links above, but that's just the REPL tool. Primarily, [Babel](https://babeljs.io/) is a really powerful transpiler. You can use most of ES6 and it transpiles it to ES5. Of course, efficiency may go out the window with a transpiler... – T.J. Crowder Jun 14 '15 at 21:01