[Solved] Fibonacci with closure in JavaScript

  

3
Topic starter

Write a JS function that when called, returns the next Fibonacci number, starting at 0, 1. Use a closure to keep the current number.

Input:
There will be no input.

Output:
The output must be a Fibonacci number.

Example:

let fib = getFibonator();
fib(); // 1
fib(); // 1
fib(); // 2
fib(); // 3
fib(); // 5
fib(); // 8
fib(); // 13
1 Answer
2

My solution - Fibonacci with a closure in JavaScript:

let fib = (function () {
    let f0 = 0;
    let f1 = 1;
 
    return function () {
        let oldf0 = f0;
        let oldf1 = f1;
 
        f0 = oldf1;
        f1 = oldf0 + oldf1;
 
        return f0;
    }
})();
 
console.log(fib());//->1
console.log(fib());//->1
console.log(fib());//->2
console.log(fib());//->3
console.log(fib());//->5
console.log(fib());//->8
console.log(fib());//->13
Share: