Why does destructuring work differently than with classic assignment in Javascript (ES6)?

As you can see here, we set the “fibonacci” as an “iterable” object, and we loop on it with for for: of:

let fibonacci = { [Symbol.iterator]() { let pre = 0, cur = 1; return { next() { [pre, cur] = [cur, pre + cur]; return { done: false, value: cur } } } } } for (var n of fibonacci) { // truncate the sequence at 1000 if (n > 1000) break; console.log(n); } 

As expected for the loop, writing to the console writes 1,2,3,5,8, ..

BUT

if I write pre = cur; cur = pre + cur; pre = cur; cur = pre + cur; instead of [pre, cur] = [cur, pre + cur];

console.log will write 2,4,8,16, ..

Why? Isn't it just breaking the way to set multiple values ​​on the same line? How can we explain the difference in purpose?

+5
source share
1 answer
 pre = cur; cur = pre + cur; 

With the pre assignment, you have lost the old pre value, and the next assignment is incorrect.

 pre cur comment values --- --- ---------------- ------- 0 1 start values * 1 1 pre = cur 1 2 cur = pre + cur * 2 2 pre = cur 2 4 cur = pre + cur * 
 [pre, cur] = [cur, pre + cur]; 

Destination Destination stores values ​​until the entire array is assigned.

+6
source

Source: https://habr.com/ru/post/1275914/


All Articles