(() => {
function l() { console.log('l()'); return 'l'; }
function r() { console.log('r()'); return { l: 1 }; }
function x() { console.log('x()'); return 'x'; }
function o() { console.log('o()'); return _o; }
var _o = {};
({ [l()]: o()[x()] } = r());
console.log('test1', _o.x);
})();
(() => {
function r() { console.log('r()'); return 'r'; }
function x() { console.log('x()'); return 'x'; }
function o() { console.log('o()'); return _o2; }
var _o2 = {};
o()[x()] = r();
console.log('test2', _o2.x);
})();
For test1
, which one is it?
-
r
→l
→o
→x
-
l
→o
→x
→r
-
r
→o
→x
→l
For test2
... just run it yourself. The result being "surprising" might be an understatement.
Top comments (3)
Blind guest. Starting from second IIFE, based on fact that JS support optional chaining
?.[]
and null coalescing assignment??=
, the evaluation order should be from right to left which iso -> x -> r
As for the first IIFE, wait a minute... Is that even allowed? I mean
🤔🤔🤔
Since it's assignment expression and not variable declaration (no
const
/let
) then my guess the evaluation order would be right-left-middle which meanr -> l -> o -> x
Thanks for the riddle, now I'm wondering if this even allowed 🤔
Were you surprised by the results, once you ran it yourself?
In response to your thought experiment regarding
{ key1: object?.key2 ??= defaultValue } = value
:object?.key2
would not make sense since optional chainedMemberExpression
s cannot be an lval (and I tested it and it is indeed invalid, phew... a few things do make sense!).??=
operator is not supported for default vals. I think, there is a lot to be said here, but I argue that this is a good thing. Syntactically it is simply not possible because default assignments (in current JS) are AssignmentPatterns, which unlikeAssignmentExpression
s do not allow for varyingoperator
s.I personally felt the strongest about this because I worked out normal assignments (
test2
) a long time ago, where things are nice and simple: left-to-right.Now I'm working on adding support for
{Object,Array}Pattern
s, and the order is just stupid. It makes some sense, since in order to evaluate things on the left, it needs to evaluate the right-hand side, but the fact that it is just straight up different from non-pattern based assignment is frustrating to say the least.Good thing, it does not matter too much, in most scenarios.