Search code examples
javascriptdestructuring

js destructuring assignment not work in while loop


[a,b] = [b, a+b] here not work , a b always 0 and 1.

If use a temp variable to swap the value ,that works.

function fibonacciSequence() {
  let [a, b, arr] = [0, 1, []]
  while (a <= 255) {
    arr.concat(a)
    [a, b] = [b, a + b]
    console.log(a, b) // always 0 1
  }
}
console.log(fibonacciSequence())


Solution

  • The problem is that Automatic Semicolon Insertion isn't doing what you expect. It's not adding a semicolon between

    arr.concat(a)
    

    and

    [a, b] = [b, a + b]
    

    so it's being treated as if you wrote

    arr.concat(a)[a, b] = [b, a + b]
    

    Add all the semicolons explicitly and you get a correct result.

    function fibonacciSequence() {
      let [a, b, arr] = [0, 1, []];
      while (a <= 255) {
        arr.concat(a);
        [a, b] = [b, a + b];
        console.log(a, b); // always 0 1
      }
    }
    console.log(fibonacciSequence())