I heard recursive function is powerful so instead going through loop i tried to create a function which increments a number until it reach certain points. when it reaches i trie
Well you could just use the return statement and you can check the code in the console like
var i=1;
function rec(){
i++;
console.log(i);
if(i > 100){
return i;
}else{
return rec();
}
}
console.log(rec());
rec
will either return i
(if i
is over 100) or undefined
(otherwise).
When you call it here:
console.log(rec());
i
will be 1
so it will return undefined
.
You never do anything with the return value when the return value is over 100.
You need to return the result of the recursive call:
} else {
return rec();
}
so when it is over 100, the value gets passed back up the stack.
it this kind of recursion is good then for loop?
No. It is horribly inefficient.
Try putting the following code after your function ends:
typeof rec === 'undefined'
The comment by vaultah is correct:
var i=1;
function rec(){
i++;
console.log(i);
if(i > 100){
return i;
}else{
return rec();
}
}
snippet.log(rec());
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
Let's take an example that only counts to > 5
and add some output so you can see what happens more easily (but again, stepping through the code with a debugger is the right way to see how this works):
var indent = "";
var i=1;
function rec(){
var rv;
i++;
indent += " ";
if(i > 5){
snippet.logHTML("<p>" + indent + i + " > 5, returning " + i + "</p>");
rv = i;
}else{
snippet.logHTML("<p>" + indent + i + " is not > 5, calling rec</p>");
rv = rec();
snippet.logHTML("<p>" + indent + "Got " + rv + " back from rec, returning it</p>");
}
indent = indent.substring(0, indent.length - 6);
return rv;
}
snippet.logHTML("<p>Final result: " + rec() + "</p>");
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>