Is the order of destructuring assignments guaranteed to be left-to-right? For example, in this code:
[ curItem.props, curItem ] = foo(curItem)
Where foo returns an array of two values.
Is the assignment to curItem.props
guaranteed to happen prior to the assignment to curItem
?
According to my reading of the standard it does, but it's a hard standard to read..
Yes, it is guaranteed by the Runtime Semantics: IteratorDestructuringAssignmentEvaluation, specifically the production
AssignmentElementList: AssignmentElementList , AssignmentElisionElement
It first recursively evaluates the assignments on the left side of the target expression (until it reaches the empty list), then afterwards on the last element in the list (skipping elision elements). So in your example [ curItem.props, curItem ]
, the curItem.props
reference is evaluated and assigned to before the curItem
reference.
It is however interesting to note that the entire expression on the left hand side of the =
operator is evaluated after the right hand side when using destructuring syntax, in contrast to strictly left-to-right evaluation of normal assignment targets. In
[ curItem.props ] = foo(curItem)
the curItem.props
reference is evaluated after the foo
call, while in
curItem.props = foo(curItem)[0]
it is evaluated before. See §12.15.4.
If you trust Babel to be spec-compliant, you can always try verify things yourself:
[ curItem.props, curItem ] = foo(curItem);
transpiles to
"use strict";
var _foo = foo(curItem);
curItem.props = _foo[0];
curItem = _foo[1];
_foo;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With