Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why destructuring works differently than in classic assignation in Javascript (ES6)?

As you can see here we set "fibonacci" as an "iterable" object and we loop on it with a 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 in for of loop, console log write 1,2,3,5,8,..

BUT

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

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

Why? Isn't destructuring just a way to set multiple values in a single line? How can we explain the difference in assignation?

like image 963
Moff452 Avatar asked Mar 16 '18 09:03

Moff452


1 Answers

pre = cur; cur = pre + cur; 

With the assignment to pre, you lost the old value of pre and the next assignment is wrong.

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];

The destructuring assignment keeps the values until the assignment of the whole array.

like image 188
Nina Scholz Avatar answered Nov 14 '22 23:11

Nina Scholz