I understand recursion in terms of how code is executed and why you might need it. What I am wondering about is that is it possible that function can reference itself within itself?
Given the following example:
function factorial(num) {
if(num ===0) {
return 1
}
return (num * factorial(num - 1));
}
factorial(2)
I want to understand what is happening under the hood in terms of how variables are stored in memory and how they're called and why is it possible to reference factorial inside a factorial function.
The way I understand how it is going to be executed at the moment:
- Declare a function
factorialon the stack that will reference an object on the heap. At this momentfactorialstill points to nowhere - Create an object on the heap(function) that will calculate factorial
- Call
factorial(2)which will take the reference on the stack wherefactorialpoints to, find the function on the heap and call it.
What I don't understand is that how when factorial is called, will it know what is factorial and where to find it? Is it related to closures somehow?
Another example(jest)
const someFunction = jest.fn((value) => {
expect(someFunction).toHaveBeenCalled()
})
Why I can reference someFunction inside the someFunction, as mentioned I suspect it is related to memory and how variables are stored, but I don't grasp the concept fully.,