Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the order of destructuring assignment in JavaScript guaranteed?

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..

like image 738
edA-qa mort-ora-y Avatar asked Sep 17 '25 04:09

edA-qa mort-ora-y


2 Answers

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.

like image 50
Bergi Avatar answered Sep 19 '25 20:09

Bergi


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;
like image 24
AKX Avatar answered Sep 19 '25 20:09

AKX