Combining Assignment Operators in JavaScript

In C #,

string s = "abc"; s += (s += s); Console.WriteLine(s); 

writes abcabcabc (http://ideone.com/pFNFX2). This is great because the C # specification explicitly says in section 7.16.2 that

an operation is evaluated as x = x op y, except that x is evaluated only once.

However, when reading the description of the assignment operator in section 11.3.2 of the ECMAScript 5.1 language specification, I do not see such a “only once” in the semantics of this operator. Instead, all I see is:

  • Let lref be the result of evaluating LeftHandSideExpression.
  • Let lval be GetValue (lref).
  • Let rref be the result of evaluating the AssignmentExpression.
  • Let rval be GetValue (rref).
  • Let r be the result of applying the @ operator to lval and rval.
  • Throw a SyntaxError exception if all conditions are true: (snipped)
  • Call PutValue (lref, r).
  • Return r.

Therefore, it would seem to me that the following JavaScript code doesn’t care

 var s = "abc"; s += (s += s); alert(s); 

will warn abcabcabcabc (due to PutValue on line 7 in the expression in brackets), but in any case in Chrome 22 it warns abcabcabc .

So my question is: did I misinterpret the spec, or Chrome (maybe V8?), So to speak, is something wrong?

+4
source share
1 answer

So, I think that if you unlock the operation, you have:

 s += (s += s); s = s + (s += s); s = s + (s = s + s); // Can't actually have the "s = " part, it really just "s + s" s = s + (s + s); s = s + s + s; 

This means that the result should be "abcabcabc".

+4
source

Source: https://habr.com/ru/post/1442576/


All Articles