2

i am working on simple js function... can u tell me how to replace the loop with recursive function.. providing my code below in the fiddle.. I am trying to learn js

http://jsfiddle.net/utbsgnzu/4/

function operation() {
    console.log("testing");
}

function repeat(operation, num) {
    for (var i = 0; i < num; i++) {
        operation();
    }
}

//repeat(operation, 10);
module.exports = repeat
0

3 Answers 3

3
function operation() {
    console.log("testing");
}

function repeat(operation, num) {
    if (num === 0) return;
    operation();
    repeat(operation, num-1);
}

//repeat(operation, 10);
module.exports = repeat
Sign up to request clarification or add additional context in comments.

Comments

0

Loops are iterative by nature. Recursive approach does not really fit into this situation. Anyhow, here you go. But use it only for fun, never for real :)

function repeat(func,maxruns,run){
    if(run>=maxruns){
      return;
    }
    func();
    repeat(func,maxruns,(run||0)+1);
}
repeat(operation,10);

Comments

-2
var foo = function foo() {
console.log(arguments.callee); // logs foo()
// callee could be used to invoke recursively the foo function (e.g.     arguments.callee())
}();
</script></body></html>

1 Comment

You should not use arguments.callee because it is deprecated and in ES5 you are not allowed to use it anymore: [...]Warning: The 5th edition of ECMAScript (ES5) forbids use of arguments.callee() in strict mode. Avoid using arguments.callee() by either giving function expressions a name or use a function declaration where a function must call itself.[...]