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>
Answer from Nik on Stack OverflowYour 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>
var b = 70;
function myfunction() {
b--;
if (b < 3) {
return b;
} else {
myfunction();
return b;
}
}
value = myfunction();
console.log(value);
You have to return all the way up the stack:
func2.call(this, sWord);
should be:
return func2.call(this, sWord);
You need to return the result of the recursion, or else the method implicitly returns undefined. Try the following:
function ctest() {
this.iteration = 0;
this.func1 = function() {
var result = func2.call(this, "haha");
alert(this.iteration + ":" + result);
}
var func2 = function(sWord) {
this.iteration++;
sWord = sWord + "lol";
if ( this.iteration < 5 ) {
return func2.call(this, sWord);
} else {
return sWord;
}
}
}
Purpose of return keyword in recursion? Can't I just omit that?
Recursive function logic works but in one case the returned value is wrong?!
recursion - Reason for return statement in recursive function call - Software Engineering Stack Exchange
recursion - How does return statement return values in recursive functions in JavaScript? - Stack Overflow
Videos
A return statement passes a value back to the immediate caller of the current function's call-frame. In the case of recursion, this immediate caller can be another invocation of that same function.
In most languages, if you don't use the return value of a function you called (recursively or not), either that return value gets discarded or it is a diagnosable error. There are some languages where the return value of the last function call gets automatically re-used as the return value of the current function invocation, but they don't differentiate between normal and recursive function calls.
Assuming unused return values get silently discarded, if you had written the code like this:
list *search_list(list *l, item_type x) {
if (l == NULL) return(NULL);
if (l->item == x)
return(l);
else
search_list(l->next, x); // no return!
}
then search_list would only return a defined value for an empty list (NULL) or if the first item matches the value you are searching for. As soon as the function goes into the recursive call, you don't know what the result will be, because the result of the recursive call gets discarded.
Additionally, you promise to return a value from your function, but you have a path (the recursive one) where you don't specify what value to return. Depending on the language you use, this usually results either in a mandatory diagnostic or in undefined behaviour (which is shorthand for: anything can happen and that can change at any time without notice. Don't hold anyone but yourself liable if it screws up your most important presentation). There are some situations where the missing return value might appear to work, but that might change the next time you run the program (with or without recompilation).
Two things; Returning the entire list in the case that you find the "x" you're looking for doesn't necessarily warrant using recursion, but that aside, consider the following:
Suppose you are seeking a value of X = "December", and your list is the numeric value of the months of the year, a pointer to the next month, and the l->items in the list are the spelled out names of the months. (January, February, ..., December). You need the three returns for the possible outcomes. The first, return(NULL) is needed if the list doesn't contain the X you're looking for. The second, (return(l)) returns the list, in this case, letting you know you found your "x". The last is where the stack model comes into play. Successive calls to the function would have updated local variables (specifically, l->item's) like this:
1: l->item = January
returns search_list(l->next, x)
2: l->item = February
returns search_list(l->next, x)
3-11: March, April, May, June, July, August, September, October, November
all return search_list(l->next, x)
12: l->item = December
This matches the second if() and returns your list, letting you know you found your search item.
What you have is a recursive function with two exit conditions, one for a found result, where the start and target value is equal, this returns the history and one where the start value is greater than the target value, which returns null for not found result.
The recursive machanis is to branch the calling of the function in two direction, one with adding fice, the other one by multiplying the value by three.
The branching takes place with a logical OR ||, which means if the first branch returns a truthy result, this result is taken and the other branch is never called. If the first branch returns null, a falsy value, the second branch is called.
What you finally get is a tree with branches and tests.
1 level 0
/ \
2 5 level 1
/ \ / \
3 4 6 7 level 2
That means, with the first call, it starts with 1 and goes if necessary to 2 and 3 and so on.
To get an idea, you could add a level variable to a console.log and watch what is going in every level.
level, start, history action -------------------------------------------- ---------------- 0 1 1 check next level 1 6 (1 + 5) check next level 2 11 ((1 + 5) + 5) check next level 3 16 (((1 + 5) + 5) + 5) null 3 33 (((1 + 5) + 5) * 3) null 2 18 ((1 + 5) * 3) null 1 3 (1 * 3) check next level 2 8 ((1 * 3) + 5) check next level 3 13 (((1 * 3) + 5) + 5) found (((1 * 3) + 5) + 5) result
function findSolution(target) {
function find(start, history, level) {
level = level || 0;
console.log(level, start, history);
if (start == target) return history; // exit condition 1 (found)
if (start > target) return null; // exit condition 2 (not found)
return find(start + 5, "(" + history + " + 5) ", level + 1) ||
find(start * 3, "(" + history + " * 3) ", level + 1);
}
return find(1, "1");
}
console.log(findSolution(13));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Have tried mapping out a few execution cases for your reference below. I guess the only tricky part here is the line return find(start + 5, "(" + history + " + 5) ") || find(start * 3, "(" + history + " * 3) ");
What may not be obvious is that || is called the short circuit or in JS. This means that if we do var x = a || b b is evaluated ONLY if a is not truthy.
In the context of your question, the mentioned line is essentially saying "Try going down the path of adding 5 and ONLY IF THIS FAILS (ie, returns null) Try going down the path of multiplying 3.
The recursive function find here has essentially three cases:
start == targetis true, which means we have reached the end of recursion with a solution. This returns the history stringstart > targetis true, which means we have overshot the target, return with null to indicate that this path does not lead to the solution- Neither of the two cases are valid.
Try going down the path of adding 5. If that doesn't work (we get back null),try going down the path of multiplying 3.
Sample Cases:
findSolution(0) //target=0
find(1, "1") //This goes to Case 3
find(1+5,"(1 + 5)") || find(1*3,"(1 * 3)")
find(1+5,"(1 + 5)") // This is a Case 2, returns null, try multiplying by 3 now
find(1*3,"(1 * 3)") // This is Case 2 again, returns null
null || null //Both paths lead to null, stop recursing, return null
null
null
findSolution(1) //target=1
find(1,"1") // This leads to the case 1. Return the history string
"1"
"1"
findSolution(3) //target = 3
find(1,"1") //This leads to case 3
find(1+3,"(1 + 5)") || find(1*3,"(1 * 3)")
find(1+5,"(1 + 5)") // This is a Case 2, returns null, try multiplying by 3 now
find(1*3, "(1 * 3)") // This is a case 1, return History string, recursion ends
null || "(1 * 3)"
"(1 * 3)"
"(1 * 3)"
findSolution(8) //target=8
find(1,"1") //This leads to case 3
find(1+5,"(1 + 5)") || find(1*3,"(1 * 3)") // Evaluate lhs first
find(1+5,"(1 + 5)") // This is a case 3 scenario again
find(6 + 5,"((1 + 5) + 5)") || find(6 * 3, "((1 + 5) * 3)")
find(6 + 5,"((1 + 5) + 5)") // Case 2, returns null
find(6 * 3, "((1 + 5) * 3)") // Case 2, returns null
null || null //Going down the add 5 path failed here, try multiplying 3
find(1*3,"(1 * 3)") // This is a case 3
find(3 + 5, "((1*3)+5)") || find(3 * 3, "((1 * 3) * 3")
find(8,"((1*3)+5)") // This is case 1, recursion ends, return history
"((1*3)+5)"
"((1*3)+5)" || find(..) //LHS evaluated to true, no need to do rhs
"((1*3)+5)"
"((1*3)+5)"
"((1*3)+5)"
"((1*3)+5)"
the part that i did not understand is how at the end of this code we get the output of 'olleh' basically the string reversed yad I understand how the process happened but I don't understand why and how we return it at the end we are storing any thing for example we can just do let reversedString = //somthing
I understand that we are slicing string from position 1 which means that It will remove first character and pass remaining string to reverse function. At that time you are taking the charAt(0)
but when the base is completed we just return an empty String '' but we get the result we wanted how is this happening "olleh" !!
code:
function reverse(i) {
if (i.length === 0) {
return "";
}
return reverse(i.slice(1)) + i.charAt(0);
}
console.log(reverse("hello"));I have a recursive function that seems to be returning undefined even though console.log indicates that the return statement in the function should have a value.
function fearNotLetter(str) {
function checkChar(char) {
var tempStr = str.split("");
if (tempStr[char + 1] == String.fromCharCode(tempStr[char].charCodeAt(0) + 1)) {
checkChar(char + 1);
} else {
console.log(String.fromCharCode(tempStr[char].charCodeAt(0) + 1));
return String.fromCharCode(tempStr[char].charCodeAt(0) + 1);
}
}
console.log(checkChar(0));
}My first console.log statement indicates that the statement does get the value I'm expecting, but when I return that value, my second console.log statement gives me "undefined".