# Don't understand why this variable can be called like a function?

So I was solving a codewars kata in which I need to find the n-th number of Fibonacci sequence.
Pretty simple:

``````function fibonacci(n) {
if(n==0 || n == 1)
return n;
return fibonacci(n-1) + fibonacci(n-2);
}
``````

But, this is slow when it comes to big numbers.
That’s why we were told to implement the memoization solution.

Now I could not solve it so I looked at the solution and didn’t understand something:

``````let memo = function(f) {
let cache = {};
return function(n) {
if(!cache[n]) cache[n] = f(n);
return cache[n];
}
};

let fibonacci = memo(function(n) {
if(n==0 || n == 1)
return n;
return fibonacci(n-1) + fibonacci(n-2);
});
``````

I don’t understand `let fibonacci` . What value does it hold, how?
And why can we call it like this `fibonacci(6)` and get a correct result which is 8?
I thought that when we call `memo` function with an anonymous function as an argument that we execute a memo function and that it’s result is saved inside a `fibonacci` variable. But how so that we can call that `fibonacci` as a function?

You can log out `fibonacci` to see what it is.

``````console.log(fibonacci);
/*
ƒ (n) {
if(!cache[n]) cache[n] = f(n);
return cache[n];
}
*/
``````

`memo` is a higher-order function, it takes a function and returns a function, that is all it does (well it also creates a Closure). The function it returns is what is assigned to `fibonacci`. You can call `fibonacci` like a function because it is a function.

2 Likes

Oh, I finally get it!
So `memo` returns a function and it gets assigned to `fibonacci`, so that’s why this works:

``````fibonacci(6)     // output is 8
``````

Thanks for the explaination!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.