2

Related to: How to fix Eslint error "prefer-destructuring"?.

I Have:

method (v100) => {
    let L,
        H;
    if (v100 <= 70) {
        const obj = {L: 1, H: 2};
        L = obj.L;
        H = obj.H;
    } else {
        L = ((0.8353 * (v100 ** 2)) + (14.67 * v100)) - 216;
        H = ((0.1684 * (v100 ** 2)) + (11.85 * v100)) - 97;
    }
    return ((L - 40) / (L - H)) * 100
}

and changed it to

{ L } = obj;
{ H } = obj;

as written in the answer. But now I get an Unexpected token error.

It should also be possible to write it like this, right?:

{ L, H } = obj;
Tom M
  • 2,815
  • 2
  • 20
  • 47
  • As stated, it throws an unexpected token error – Tom M Aug 02 '18 at 14:41
  • 3
    Try `({ L, H } = obj);` to not treat curly braces as blocks. – pishpish Aug 02 '18 at 14:43
  • @destoryer this fixed it, thank you! Add it as an answer with a little more explanation and I'll accept and upvote – Tom M Aug 02 '18 at 14:45
  • @31piy added more code to make the error reproducible – Tom M Aug 02 '18 at 14:46
  • I'm confused by your code. If `v100 > 70`, you're going to return `((undefined - 40) / (undefined - undefined)) * 100`. Did you omit a bunch of code to post here? – mccambridge Aug 02 '18 at 14:58
  • @mccambridge yes I omitted the else. Wait a second, I'll add it too. – Tom M Aug 02 '18 at 15:00
  • Ah, okay. Yeah, I repeated @destoryer 's suggestion. Since you don't have a `var/let/const` keyword, it's trying to treat your curlies as an object or block. – mccambridge Aug 02 '18 at 15:05
  • 1
    I would really recommend using `const obj = {L: 1, H: 2}; const {L, H} = v100 <= 70 ? obj : {L: 0.8353 * v100**2 + 14.67 * v100 - 216, H: 0.1684 * v100**2 + 11.85 * v100 - 97};` for simplicity – Bergi Aug 02 '18 at 18:28
  • @Bergi thanks for your response but due to readability issues we also have no-ternary in use. Also, I'd say this isn't exactly a dupe as the question differs from the linked post. – Tom M Aug 15 '18 at 09:05

1 Answers1

1

Try:

({ L, H } = obj);

Quoting from MDN web docs

The round braces ( ... ) around the assignment statement is required syntax when using object literal destructuring assignment without a declaration.

{a, b} = {a: 1, b: 2} is not valid stand-alone syntax, as the {a, b} on the left-hand side is considered a block and not an object literal.

However, ({a, b} = {a: 1, b: 2}) is valid, as is var {a, b} = {a: 1, b: 2}

NOTE: Your ( ... ) expression needs to be preceded by a semicolon or it may be used to execute a function on the previous line.

Community
  • 1
  • 1
James
  • 5,635
  • 2
  • 33
  • 44