javascriptecmascript-2018

How to use special characters (like hyphen) in destructuring assignment syntax?


I'm curious of why that seems impossible:

const {a, b, 'special-one'} = { a:1, b:2, 'special-one': 3 };
// output => missing : after property id

Will it be possible to find that syntax working in future ES versions ?

Thanks for your lights :)


Solution

  • Rename the variable within the destructure statement, you can't have a variable with a hyphen in it's name. You can rename using the syntax below, see MDN: Assigning to new variable names

    A property can be unpacked from an object and assigned to a variable with a different name than the object property.

    const {
      a,
      b,
      'special-one': specialOne
    } = {
      a: 1,
      b: 2,
      'special-one': 3
    };
    
    console.log(specialOne);