The best solution for your problem is closures
.which helps to return the function from the function and the inner function stores the value of the variables of outer function without regards of function call.
This fibonacci function is written using closure to generate the Fibonacci series by just calling the function without storing the variables curr
, prev
in global scope.
function fibonacci() {
let prev = 1, curr = 1;
return function () {
const next = prev + curr;
[prev, curr] = [curr, next];
return prev;
};
}
let next_fibonacci = fibonacci();
for(let i=1; i <= 5;i++){
console.log(next_fibonacci());
}
If you don't know about closures then go and refer closures