Search code examples
javascriptecmascript-6destructuring

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?


Solution

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