DEV Community

Cover image for [JS Quiz] Guess the Order of Execution (chances of getting this right are slim)
Domi
Domi

Posted on

[JS Quiz] Guess the Order of Execution (chances of getting this right are slim)

(() => {
  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);
})();
Enter fullscreen mode Exit fullscreen mode

For test1, which one is it?

  1. rlox
  2. loxr
  3. roxl

For test2... just run it yourself. The result being "surprising" might be an understatement.

Top comments (3)

Collapse
 
drsensor profile image
૮༼⚆︿⚆༽つ

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 is o -> x -> r

As for the first IIFE, wait a minute... Is that even allowed? I mean

{ key1: object.key2 } = value
Enter fullscreen mode Exit fullscreen mode

🤔🤔🤔
Since it's assignment expression and not variable declaration (no const/let) then my guess the evaluation order would be right-left-middle which mean r -> l -> o -> x

Thanks for the riddle, now I'm wondering if this even allowed 🤔

{ key1: object?.key2 ??= defaultValue } = value
Enter fullscreen mode Exit fullscreen mode
Collapse
 
domiii profile image
Domi

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 chained MemberExpressions cannot be an lval (and I tested it and it is indeed invalid, phew... a few things do make sense!).
  • The ??= 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 unlike AssignmentExpressions do not allow for varying operators.
Collapse
 
domiii profile image
Domi

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}Patterns, 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.