Yan Li Yan Li - 22 days ago 7
Javascript Question

Why doesn't this for loop work when I simple change two expression's order

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?

Answer

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]