kca
kca

Reputation: 6113

error "Invalid parenthesized assignment pattern" background info

In my React project, I got this error:

SyntaxError: ... Invalid parenthesized assignment pattern
const add = (a, b) = { return a + b; };
             ^

I do understand the error, but I am surprised that I could not find any information about it.

What I want to understand

I do understand the problem here (the '>' is missing in this arrow function), but I wonder (1) where this error comes from exactly (not the Browser?), and (2) where could I find information about it.

The error message obviously interprets this as a wrong assignment, not as a wrong arrow function:

const add = (a, b) = { return a + b; };
// error ----^
// actually wrong --^

Where it obviously does not come from:

If I write the same statement in the NodeJs CLI, I get:

const add = (a,b) = { return ''; }
            ^^^^^
ReferenceError: Invalid left-hand side in assignment

in the Firefox console:

SyntaxError: invalid assignment left-hand side

Note that I am using Firefox for development, but the error message during development is different than the error message when I try the same in the Firefox console (Invalid parenthesized assignment pattern vs. SyntaxError: invalid assignment left-hand side)

Upvotes: 5

Views: 6205

Answers (2)

kca
kca

Reputation: 6113

The error message comes from the Babel parser.

The text is defined in babel / packages / babel-parser / src / parse-error / standard-errors.ts:

InvalidParenthesizedAssignment: "Invalid parenthesized assignment pattern.",

Documentation

These kind of errors are (apparently) not documented on a user level, but there is some explanation in the source code in babel / packages / babel-parser / src / util / expression-scope.ts:

line 32:

- MaybeArrowParameterDeclaration
  A scope that represents ambiguous arrow head e.g. `(x)`. Errors will be recorded
  alongside parent scopes and thrown when `ExpressionScopeHandler#validateAsPattern`
  is called.

line 164:

* A parenthesized identifier (or type assertion) in LHS can be ambiguous because the assignment
* can be transformed to an assignable later, but not vice versa:
* For example, in `([(a) = []] = []) => {}`, we think `(a) = []` is an LHS in `[(a) = []]`,
* an LHS within `[(a) = []] = []`. However the LHS chain is then transformed by toAssignable,
* and we should throw assignment `(a)`, which is only valid in LHS. Hence we record the
* location of parenthesized `(a)` to current scope if it is one of MaybeArrowParameterDeclaration
* and MaybeAsyncArrowParameterDeclaration

Upvotes: 0

GuruDev Techno
GuruDev Techno

Reputation: 39

Since you are using the ES6 arrow function, you have to define =>

const add = (a, b) = { return a + b; }; // here you missed arrow for function **=>**

const add = (a, b) **=>** { return a + b; }; //modified by adding **=>**

Upvotes: 3

Related Questions