I've been reading more specifically into the closure concept of programming, particularly pertaining to Javascript. I'm not quite there yet in understanding how it's any different from the Javascript code I've been writing for years though. I understand the concept of recursion as well, but I'm wondering, how are closures and recursion similar? Do I understand correctly that recursion, in and of itself, is a type of closure?
Closure:
function init() {
var name = "Stack Overflow";
function displayName() {
alert(name);
}
displayName();
}
init();
Recursion:
function factorial(num) {
if(num < 0)
return -1;
else if(num == 0)
return 1;
else
return (num * factorial(num - 1));
}
alert(factorial(8));
I think I'm beginning to understand that a closure is nothing more than having a function within a function, with the inside function having access to the outside function via scoping. Could there be a recursive closure? I mean, while my example of recursion isn't exactly an example of closure as well, could it at least happen? I'm trying to understand how recursion and closures are similar, different, or if they're even comparable by all. Are there any examples to maybe describe this?