Yes, a Fibonacci series - what fun!
Here is a slightly condensed version of it with only two variabes (a
and b
):
function calc (max) {
for (let a = 0, b = 1; b < max;) console.log(([a,b] = [b,a+b])[1])
}
calc(100);
Update
Here a version that will only return the last two values (for later use in your HTML): the last one below and the first one above the target value max
:
function calc (max) {
for (var a = 0, b = 1; b < max;) [a,b] = [b,a+b];
return [a,b];
}
console.log(calc(100));
Sorry for overloading you. I have to admit, I didn't carefully read all the text in your question. In particular your ADHD situation. No worries, I will try to explain what I did now in more detail so you will be able to follow:
1. My loop is set up in a for()
loop - like in Alexey's solution:
for (var a = 0, b = 1; b < max;)
This means
- that initially the variables
a
and b
will be set upt to contain the values 0
and 1
(the two assignemts are separated by the ,
-opertor).
- The second part of the
for
expression (b < max
) checks whether b
is still below the maximum value max
and only then will the loop expression be executed.
- A third expression (behind the
;
-separator) does not exist.
2. The loop expression ...
[a,b] = [b,a+b]
... makes use of the new ES6 feature of destructuring. It is a shorthand version of the otherwise three separate assignement statements:
tmp = b; // buffer the value of b
b = a+b; // do the sum and re-assign to b
a = tmp; // assign the original value of b to variable a
The ES6 construct is helpful here,
- as it buffers the calculated results of the right hand side before assigning it to the array on the left hand side of the equation.
- Only then (in the destructuring phase) will the newly calculated values be assigned to the variables
a
and b
.
3. The return value(s)
As I was uncertain as to which value you wanted to have returned from the function I chose to return two values in an array: one below and one above the target value max
.
return [a,b];
It is up to you to adapt the return statement to better suit your needs: either return a;
or return b;
.
4. var
instead of let
Please note that I used var a=0, b=1
instead of let a=0, b=1
in the for()
loop of my later version, as I needed to access these variables outside the scope of the for()
loop. The var
defines a variable with function scope (instead of block scope).
I hope that this will help you a little more than my admittedly fairly cryptic first version.
Alternative version (variation)
If you are looking for a function that will retun the n-th value of the Fibonacci series you can do it like this:
function fib (n) {
for (var a = 0, b = 1; n--;) [a,b] = [b,a+b];
return b;
}
// test the function fib with n = 1, ..., 19
for (let i=1; i<20; i++) console.log(`fib(${i}):`,fib(i));