wgf4242
wgf4242

Reputation: 831

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())

Upvotes: 0

Views: 106

Answers (2)

Nidhi Gupta
Nidhi Gupta

Reputation: 41

You can use the below function as well:

    function fibonacciSequence() {
      let [a, b] = [0, 1];
      while (a <= 255) {

       b = a + b;
       a = b - a;
       console.log(a,b);
      }
    }
    fibonacciSequence();

Upvotes: 0

Barmar
Barmar

Reputation: 780724

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())

Upvotes: 6

Related Questions