Search code examples
javascriptecmascript-6returneslintparentheses

The "no-return-assign" - Difference between Assignment with and without Parentheses


The no-return-assign allows no asignments in a return statement. But by default it allows it when you put your assignment in parentheses.

Is there a technical difference between return (foo = 1 + 1) and return foo = 1 + 1?

I have this question because I try the following with

return createMatrixRow(
  width,
  element,
  addWidth,
  elements.concat(addWidth ? Object.assign({}, element, (element.position.width = width)) : element)
)

To avoid the error message I put element.position.width = width in parentheses.


Solution

  • No difference. In both cases, they form a single expression, except that with the parens, the expression is the grouping operator, which receives the original assignment expression and returns its result.

    It's a fairly common trait of linters to use parens to manually override assignments that may look like errors.

    For example, this will usually annoy the linter:

    while (x = re.exec(data)) {
      // do work
    }
    

    The reason being that an assignment as a condition is very often a typo, where == was intended.

    But this will often satisfy it:

    while ((x = re.exec(data))) {
      // do work
    }
    

    The otherwise superfluous parents are a way of saying "yes, I know this is an assignment, so I'll wrap it with these unnecessary parens to indicate that".