Is there a better solution for Javascript's order of evaluation?

Viewed 64
class foo {
  constructor(req) {
    this.req = req;
  }
  async bar() {
    this.req.baz = {};
    return 1;
  }
}
const req = {};
req.baz.boof = await new foo(req).bar();

I would have thought that JS would eval the right hand side first and req.baz would be an object before the assignment of req.baz.boof was attempted. Yet I get an error saying that boof cannot be assigned because req.baz is undefined. I know the code is terrible and should be refactored. What fixes it is this:

const temp = await new foo(req).bar();
req.baz.boof = temp;

Has anyone seen this before? Is this the best workaround, assuming I can't refactor all the related code?

1 Answers

If you look at the specification,

  1. If LeftHandSideExpression is neither an ObjectLiteral nor an ArrayLiteral, then
    a. Let lref be the result of evaluating LeftHandSideExpression. [...]

I.e. compiler/interpreter needs to evaluate left side first to validate and determine the type for the right side expression.

I can't think of a better fix than proposed in the question.

P.S. It is not a contradiction to the right-to-left rule. RTL means that

x = y = 2;

is evaluated as

x = (y = 2);

instead of

(x = y) = 2;
Related