Reputation: 5308
function findSequence(goal) {
var find = function (start, history) {
if (start == goal)
return history;
else if (start > goal)
return null;
else
return find(start + 5, "(" + history + " + 5)") ||
find(start * 3, "(" + history + " * 3)");
}
return find(1, "1");
}
var sequence = findSequence(24);
Is sequence
a closure function? If yes, is this preferable to use closures in this way? I was taught by web resources to avoid closures.
UPDATE:
I was asked in the comments to show web resources. These are more reliable resources that i have seen in the web.
1.MDN - Closures under "Performance considerations".
2.Addy Osmani's Article under "Garbage Collection - Closures".
3.MSDN - see "Closures" section.
4.Stack Overflow Post - see accepted answer.
6.another intresting article - see last two paragraphs.
Upvotes: 0
Views: 92
Reputation: 665574
No, sequence
is no function at all; so it is no closure.
The find
function is a closure. It's recursively called and maintaining a reference to the goal
variable from the parent scope. Yet it does not outlive the findSequence
call, so we don't utilize this feature. The usage of an extra function for recursion is very fine here.
I was taught to avoid closures.
No need for that. Maybe they need little more memory, but don't care about that. If they come in handy (which happens very often due to their power) and you find them useful, then use them. Don't do premature optimisation. Only if you get actual performance problems, you might look into working around them.
Upvotes: 2
Reputation: 12335
No, It is not. You are just recursing in the function and returning the result. Closure is created when you do something like this.
function getFun(param){
var x = 5;
return function(){
return param * x; // Here closure is created, variables param and x are retained.
}
}
var foo = getFun(5);
alert(foo()); // alerts 25
Upvotes: 0
Reputation: 909
sequence
is a variable which is assigned the returned value from findSequence(24);
Upvotes: 0
Reputation: 944568
Is sequence a closure function?
No. It just does recursion within a scope.
Upvotes: 1