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 Overflow
Discussions

Purpose of return keyword in recursion? Can't I just omit that?
So that the function stops at that return. Otherwise would call the generate and then continue inside the original More on reddit.com
🌐 r/learnjavascript
27
24
June 6, 2022
Recursive function logic works but in one case the returned value is wrong?!
Please help me I’ve spent two hours unsuccessfully debugging this one case. I used a recursive function to do this problem. It makes sense to do it this way as you can scale it. A for loop would go through the array one by one. My recursive function splits the array in two, puts the number ... More on forum.freecodecamp.org
🌐 forum.freecodecamp.org
1
0
April 10, 2018
recursion - Reason for return statement in recursive function call - Software Engineering Stack Exchange
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. More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
June 17, 2013
recursion - How does return statement return values in recursive functions in JavaScript? - Stack Overflow
Can someone please explain me how this recursive function works. I can't understand how the values are returned in call stack. Could you please explain with some graphics, representing the execution contexts. It would be better if you can explain the way as explained in the Udemy course JavaScript-... More on stackoverflow.com
🌐 stackoverflow.com
January 19, 2018
🌐
Better Programming
betterprogramming.pub › importance-of-the-return-keyword-in-recursive-javascript-functions-d12203c30d1a
Importance of the Return Keyword in Recursive JavaScript Functions | by Matt Cummings | Better Programming
March 19, 2020 - Note: This function works for numbers up to a certain threshold, as binary numbers that are of a certain length are incorrectly rounded via JavaScript. That being said, its efficacy has no bearing on the logic or examples contained in this article. Simple enough, right? It does what it needs to do, yet when I throw a number in there and call this function, all I get is undefined. Logging my results to the console shows what I’m expecting, but why isn’t this value actually being returned?
🌐
Reddit
reddit.com › r/learnjavascript › purpose of return keyword in recursion? can't i just omit that?
r/learnjavascript on Reddit: Purpose of return keyword in recursion? Can't I just omit that?
June 6, 2022 - It is not exiting the function entirely. Each value that is returned is sent back to that previous point of call. As for the illustration with the tree, you may have noticed that as the recursion is happening, you're going down the tree.
🌐
JavaScript.info
javascript.info › tutorial › the javascript language › advanced working with functions
Recursion and stack
The first solution we could try here is the recursive one. ... function fib(n) { return n <= 1 ? n : fib(n - 1) + fib(n - 2); } alert( fib(3) ); // 2 alert( fib(7) ); // 13 // fib(77); // will be extremely slow! …But for big values of n it’s very slow.
🌐
Medium
medium.com › swlh › recursive-functions-in-javascript-9ab0dd97e486
Recursive Functions in JavaScript | by Ross Mawdsley | The Startup | Medium
August 28, 2020 - When first called, reverseString() immediately calls itself, but with str.substr(1) as an argument {The substr() method, when given just one argument, simply returns a substring cut from the original: omitting a set number of characters from the front of the string, as stipulated by the integer value that’s passed as an argument}. So in the above example, the first character will be removed, giving “eversed”. This is what is passed to the 2nd recursive call (i.e.reverseString('eversed')) but what is returned from the first call is: reverseString('eversed') + 'r' This 2nd reverseString() call is known as a ‘nested’ function call.
Find elsewhere
🌐
Rip Tutorial
riptutorial.com › recursive function
JavaScript Tutorial => Recursive Function
If it's odd, we add zero to it. return ((value % 2 === 0) ? 1 : 0) + countEvens(arr); } It is important that such functions make some sort of sentinel value check to avoid infinite loops. In the first example above, when n is less than or equal to 1, the recursion stops, allowing the result of each call to be returned back up the call stack.
Top answer
1 of 2
21

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).

2 of 2
1

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.
🌐
JavaScript Tutorial
javascripttutorial.net › home › javascript tutorial › javascript recursive function
JavaScript Recursive Function
November 15, 2024 - function recurse() { if(condition) { // stop calling itself //... } else { recurse(); } }Code language: JavaScript (javascript) Generally, you use recursive functions to break down a big problem into smaller ones. Typically, you will find the recursive functions in data structures like binary trees and graphs and algorithms such as binary search and quicksort. Let’s take some examples of using recursive functions. Suppose that you need to develop a function that counts down from a specified number to 1.
🌐
SitePoint
sitepoint.com › blog › javascript › recursion in functional javascript
Recursion in Functional JavaScript — SitePoint
November 11, 2024 - The base case is typically a condition that the function checks before making a recursive call. If the condition is met, the function returns a value and stops calling itself. In JavaScript, recursion works by a function calling itself until it reaches a base case.
🌐
Medium
medium.com › functional-javascript › recursion-282a6abbf3c5
Recursion. Recursion, Tail Calls, Proper Tail… | by Santosh Rajan | Functional JavaScript | Medium
April 11, 2014 - Otherwise calling the function will lead to an infinite loop. A tail call is a function call whose return value is used as the callers return value. In the function above return factorial(n — 1, n * accumulator) is a tail call.
🌐
Linux Hint
linuxhint.com › javascript-recursive-function
JavaScript Recursive Function
April 5, 2022 - Linux Hint LLC, [email protected] 1210 Kelly Park Circle, Morgan Hill, CA 95037 Privacy Policy and Terms of Use
Top answer
1 of 3
1

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; }

2 of 3
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:

  1. start == target is true, which means we have reached the end of recursion with a solution. This returns the history string
  2. start > target is true, which means we have overshot the target, return with null to indicate that this path does not lead to the solution
  3. 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)"
🌐
Medium
medium.com › swlh › getting-started-with-recursive-functions-in-javascript-ed6fcfaf1dc5
Getting Started with Recursive Functions in JavaScript | by Joseph Emswiler | The Startup | Medium
January 22, 2021 - A recursive function is a function that loops by calling itself. It (obviously) gets more complicated than that, but we can get started with recursion with this oversimplified explanation…
🌐
Medium
samah-gaber.medium.com › recursion-in-javascript-52e2a3a59627
Recursion in Javascript. The function calls itself until someone… | by Samah Gaber | Medium
October 21, 2020 - It’s simply our function calling itself. In the factorial example, return x * factorial(x — 1); is where the recursion actually happens. We’re returning the value of the number x multiplied by the value of whatever factorial(x-1) evaluates to.
🌐
Reddit
reddit.com › r/learnjavascript › how javascript return work in a recursive function
r/learnjavascript on Reddit: how javascript return work in a recursive function
August 14, 2022 -

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"));
Top answer
1 of 2
5
Imagine your boss gave you a bag with 1000 pieces of candy and asked you to sort it into a bucket for each type. You say well I don’t want to do all this let me take out one piece and pass it off to some other guy to the rest. So you pass it along and tell the next guy to do the same thing but he has the same idea as you and he also takes out a piece of candy and passes it a long. Then 998 passes go by and the guy looks inside the bag and says well this is easy there’s only one piece I’m going to place this inside a bucket and tell the guy before me that Im done. He then passes it back to the guy before him and that guy places his piece in a bucket and says I’m done and passes it to the guy before him. After many passes back it gets to the you who sees that the candy is all sorted into buckets and says I’m done and you give it to your boss who’s happy he didn’t have to sort 1000 pieces of candy by hand.
2 of 2
4
when the base is completed we just return an empty String '' but we get the result we wanted how is this happening "olleh" !! I don't have access to a computer right now to type out how the empty string gets populated in reverse order; hence, I am sharing the below where I have shown how an empty array gets populated in reverse order. Have a look and see if it helps you corelate. https://www.reddit.com/r/learnjavascript/comments/wf6yzb/help_needed_wrapping_my_head_around_recursion_in Hi, Understanding the below might help: If a function A calls another function B, then A will remain paused until B returns and only then can A return after executing the remaining code in it. With the above understanding, execute the code below and see if it helps understand that with n = 3 how essentially 4 functions are run and how each function fills up the empty array that the 4th function returns when n = 0. function f3(n){ console.log("n in f3 = ", n) let arr = f2(n-1) console.log("arr in f3 before unshift = ", arr) arrCopy = [...arr] arrCopy.unshift(n) return arrCopy // [3, 2, 1] } function f2(n){ console.log("n in f2 = ", n) let arr = f1(n-1) console.log("arr in f2 before unshift = ", arr) arrCopy = [...arr] arrCopy.unshift(n) return arrCopy // [2, 1] } function f1(n){ console.log("n in f1 = ", n) let arr = f0(n-1) console.log("arr in f1 before unshift = ", arr) arrCopy = [...arr] arrCopy.unshift(n) return arrCopy // [1] } function f0(n){ console.log("n in f0 = ", n) let arr=[] console.log("arr in f0 = ", arr) if(n==0) return arr // [] } console.log("final result = ", f3(3)) Output: n in f3 = 3 n in f2 = 2 n in f1 = 1 n in f0 = 0 arr in f0 = Array (0)[ ] arr in f1 = Array (0)[ ] arr in f2 = Array (1)[ 1 ] arr in f3 = Array (2)[ 2,1 ] final result = Array (3)[ 3,2,1 ] undefined
🌐
Reddit
reddit.com › r/javascript › recursive function is returning "undefined"
r/javascript on Reddit: Recursive function is returning "undefined"
December 30, 2017 -

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".