0

Creating an array of fibonachi numbers:

function sumFibs(num) {
  var list = [1,1];
  var next = list[list.length-1] + list[list.length-2];

  while (true) {
    if (next<=num) {
      list.push(next);
    } else {
    return list;
    }
  }
}

sumFibs(10);

This gives me infinite loop.

If I add next = list[list.length-1] + list[list.length-2]; after list.push(next); it works fine. Why?

4
  • 1
    You only call your function once and there is no incrementation within your loop. num ALWAYS = 10 and next ALWAYS = list[list.length-1] + list[list.length-2]; so...it will go on for ever. As you note, when you add incrementation within the while loop it works as it should. Commented Sep 25, 2017 at 22:48
  • 1
    If you modify neither next nor num in the body of the loop, how could the condition next <= num ever switch from being true to being false? Of course you have an infinite loop. Commented Sep 25, 2017 at 22:49
  • You only assign to the next variable once, outside of the loop, so nothing changes inside the loop to ever fufill the return condition. BTW, you should use that condition as the condition for the while loop, instead of true, and return after the loop. Commented Sep 25, 2017 at 22:53
  • next is a Primitive value so it's not changing. The length of list is changing as you're pushing onto it. Commented Sep 25, 2017 at 22:59

1 Answer 1

1

The next variable does not update every time you reference it. If it did, imagine how confusing programs would be.

You can move the evaluation of the last members of the list to the loop.

function sumFibs(num) {
  var list = [1, 1];
  var next = list[list.length - 1] + list[list.length - 2];

  while (true) {
    if (next <= num) {
      list.push(next);
      next = list[list.length - 1] + list[list.length - 2]
    } else {
      return list;
    }
  }
}

console.log(sumFibs(10));

Here's a different implementation that doesn't rely on a loop.

function sumFibs(num) {
  return f(num, [1, 1]);

  function f(n, arr) {
    var next = arr[arr.length - 1] + arr[arr.length - 2];
    return next <= num ? f(n, arr.concat(next)) : arr;
  }
}

console.log(sumFibs(10));

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.