javascriptjsonobject-destructuring

Escape reserved keywords in object destructuring assignment


Is it possible to use reserved keywords in an object destructuring assignment?

Specifically I am trying to handle JSON with property named default.

//Doesn't compile
class FooBar {
  constructor({foo, default}) {
    this.foo = foo;
    this.default = default;
  }
}
/* json from server {foo: "bar", default: true} */
new FooBar(json);

Solution

  • It's possible to use them as a property name, but not as a variable name. Choose a different target:

    class FooBar {
      constructor({foo, default: def}) {
        this.foo = foo;
        this.default = def;
      }
    }