You can try all the examples on this page directly in the development console of this page (`F12`).

# JavaScript

## Easy loop

``````let target = 10;
let c, a = 0, b = 1;
for(let i = 0; i < target; i++) {
c = a, a = a + b, b = c;
}
console.log(a);``````

### Easy loop using `BigInt`

``````let target = 10;
let a = 0n, b = 1n;
for(let i = 0; i < target; i++) {
b = [a, a = a + b];
}
console.log(a);``````

## Easy recursive

``````const fib = (x) => x < 3 ? 1 : fib(x - 1) + fib(x - 2);
console.log(fib(10));``````

### With caching and `BigInt`

``````const cacheFn = fn => {
const cache = {};
return (cacheKey, ...rest) => {
if(cache[cacheKey]) return cache[cacheKey];
const result = fn(cacheKey, ...rest);
cache[cacheKey] = result;
return result;
}
}

const fib = (x, fn) => x < 3 ? 1n : fn(x - 1, fn) + fn(x - 2, fn);
const cachedFib = cacheFn(fib);
console.log(cachedFib(10, cachedFib));``````

## Tail-recursive

``````const fib = (t, a = 0n, b = 1n) => t < 0 ? b : fib(t - 1, a + b, a);
console.log(fib(10));``````

### Tail-recursive using `BigInt`

``````const fib = (t, a = 0n, b = 1n) => t < 0 ? b : fib(t - 1, a + b, a);
console.log(fib(10));``````

## Fast doubling

✔️
Really fast
Use this method for big `n`
``````function fib(q) {
if(q == 0) return [0n, 1n];
const [a, b] = fib(Math.floor(n / 2));
const c = a * (b * 2n - a);
const d = a * a + b * b;
if(q % 2 == 0) return [c, d];
return [d, c + d];
}
console.log(fib(10));``````

## Tuple based

``````const [a, b] = Array.from({ length: 10 }).reduce(([a, b]) => [a + b, a], [1n, 0n]);
console.log(b)``````

## List-based

Get all Fibonacci numbers in a list.

## Generator

Get the next Fibonacci number.

## Tail-recursive generator

Get the next Fibonacci number.

## Fast doubling generator

✔️
Suitable for large `n`
``````function* fib(q, depth=0) {
if(q == 0) return [0n, 1n];
const [a, b] = yield* fib(Math.floor(q / 2), depth+1);
const c = a * (b * 2n - a);
const d = a * a + b * b;
yield depth;
if(q % 2 == 0) return [c, d];
return [d, c + d];
}
const n = 10;
const gen = fib(n);
const fn = () => {
const {done, value} = gen.next();
if(done) { clearTimeout(timeout); return console.log(n < 1000000 ? value : "Yay"); }
console.log("Depth", value)
timeout = setTimeout(fn, 1)
};
let timeout = setTimeout(fn, 1)``````
⚠️
For larger `n`, do not log the return value to console
Printing the value to the console takes longer than the entire calculation of it!

## Recursive web workers

⚠️
Bigger `n` will crash your browser tab!
This is due to the high number of threads spawned.
This method will overflow without warning for large `n`!