Skip to content
Advertisement

Why the right side of a destructuring assignment ignores an index increment made in its left part

Since the postfix ++ exists in languages, the following will always make v[0] ← v[1]:

v = [8, 7, 6, 5];
i = 0;

v[i++] = v[i];

console.log(v[0]); // gives 7

Now with destructuring assignment, it’s different – I could only test with Chrome and Firefox:

v = [8, 7, 6, 5];
i = 0;

[v[i++]] = [v[i]]; // does "v[0] ← v[0]"

console.log(v[0]); // gives 8

Both would end up with i expected value of 1. I tried many other king of variable assignments in the left part of a destructuring assignment and all the time, those variable assignments were ignored by the right side of the main destructuring one. Then after destructuring, the new variable value was back there. Why?

Advertisement

Answer

JavaScript is generally interpreted left-to-right, that’s what happens in v[i++] = v[i];.

Only in a destructuring assignment, the target is evaluated after the value, since with defaults the evaluation might depend on the value itself. Evaluating property names beforehand might have been possible, but would have been more complicated, leading to the apparent inconsistency.

In any case, just don’t mutate your variables in property name computations, it’s confusing for the reader whether you know the exact semantics or not.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement