0

I have the following code

let { searchTerm: searchTerm = '' } = this.state;

searchTerm = decodeURIComponent(searchTerm)

Which works, but I was wondering if it was possible to embed the expression (decodeURIComponent call) inside the destructuring like

const { decodeURIComponent(searchTerm) : searchTerm = '' } = this.state;
//or
const { searchTerm = searchTerm ? decodeURIComponent(searchTerm) : '' } = this.state;

But those syntaxes are illegal or plain don't work. Haven't found documentation that shows how to, yet, looking at the grammar, it seems it somehow should work, ie it uses the same "initializer" rule

From this grammar rule http://www.ecma-international.org/ecma-262/6.0/#sec-destructuring-assignment

look at AssignmentElement definition

Then go to http://www.ecma-international.org/ecma-262/6.0/#sec-object-initializer

then look at Initializer definition

Then look at http://www.ecma-international.org/ecma-262/6.0/#sec-assignment-operators

FZs
  • 16,581
  • 13
  • 41
  • 50
  • 3
    At some point, it probably just makes sense to skip the destructuring: `let searchTerm = decodeURIComponent(this.state.searchTerm || "");`. – jfriend00 Jun 17 '20 at 00:32
  • 1
    The *Initialiser* is the `''` expression after the `=`. The `decodeURIComponent(searchTerm)` in your code clearly is no *IdentifierReference* – Bergi Jun 17 '20 at 08:17
  • 1
    Also see [early errors](http://www.ecma-international.org/ecma-262/6.0/#sec-destructuring-assignment-static-semantics-early-errors) of the assignment expression. And when you're using `const`, it's actually a [*BindingPattern*](http://www.ecma-international.org/ecma-262/6.0/#sec-destructuring-binding-patterns) not an assignment. – Bergi Jun 17 '20 at 08:26

0 Answers0