2

For the following fibonacci function, it works as expected:

function fibonacci(n) {
  var nums = []
  var a = b = 1
  for (let i = 0; i < n; i++) {
    [a, b] = [b, a + b]
    nums.push(a)
  }
  return nums
}

console.log(fibonacci(5));
// outputs: [1,2,3,5,8]

but after I changed two statements' order, it doesn't work:

function fibonacci(n) {
  var nums = []
  var a = b = 1
  for (let i = 0; i < n; i++) {
    nums.push(a)
    [a, b] = [b, a + b]
  }
  return nums
}

console.log(fibonacci(5));
// outputs: [1,1,1,1,1]

What's wrong with it?

Barmar
  • 741,623
  • 53
  • 500
  • 612
Yan Li
  • 63
  • 4

1 Answers1

5

It's because you left out the semicolon at the end of the line

nums.push(a)

So it's merging the two lines into:

nums.push(a)[a, b] = [b, a + b]

This doesn't reassign the a and b variables, it's indexing an array.

You should really get out of the bad habit of omitting semicolons. Javascript allows it, but as you see in this example it doesn't always infer the statement breaks where you assume they would be.

function fibonacci(n) {
  var nums = [];
  var a = b = 1;
  for (let i = 0; i < n; i++) {
    nums.push(a);
    [a, b] = [b, a + b];
  }
  return nums;
}

console.log(fibonacci(5));
// outputs: [1,1,1,1,1]
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Semi–colon insertion follows set rules, so really it's the OP that didn't correctly infer where semi–colons would (and would not) be inserted and the consequence. ;-) – RobG Nov 15 '16 at 02:57