I need to store the return value in a variable.
I want to know how to fix this code. I know that if the value of b would be 3, I would get value=2, but if the function does more than one iteration I get unidentified. I read that I should use the callback or something but I don't know how, also an explanation of why my code doesn't work and how should I fix it. (Of course this code is for demonstration purpose as if I would show you the original it might get confusing.) Thanks a lot!
var b = 70;
function myfunction() {
b--;
if (b < 3) {
return b;
} else {
myfunction();
}
}
value = myfunction();
console.log(value);
Recursion is a method of programming or coding a problem, in which a function calls itself one or more times in its body. Usually, it is returning the return value of this function call. If a function definition satisfies the condition of recursion, we call this function a recursive function.
You don't "break" out of recursive functions. Trying to do so says you're thinking about them the wrong way. Currently your recursive call is ignoring the output, which means that the recursion is pointless; whatever is_pal(middle(str)) returns has no effect on the return value of your function.
Now, one important thing before coding a recursion is that you must understand how mathematically it is supposed to work. In the case of sum of n numbers we know that if sum of n-1 numbers is known we could return that sum + n . Now what if do not know that sum . Well, we find sum of n-2 terms and add n-1 to it.
Your code: myFunction()
will return void/undefined
on first call, it is not a recursive approach.
Following example is a recursive approach. A recursive function usually receive an argument to be processed and return a final value that bubbles(returned) up to the first caller.
function myfunction(b){
b--;
if(b<3) return b;
else return myFunction(b);
}
When you call a recursive function, you should prepare a test for an escape. Otherwise you might end up in an infinite loop.
Example of an infinite recursive
function badFunction(){
return badFunction();
}
// DON'T call badFunction()
Recursive Example
var b = 70;
var safety = 1000;
function myfunction(local_b) {
if(safety<0) return;
safety--;
// main task
local_b--;
if (local_b < 3) {
return local_b;
}
return myfunction(local_b);
}
var value = myfunction(b); // when b = 70, value = 2
console.log(value);
document.getElementById('value').innerHTML = value;
<span id="value">_</span>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With