13

Why is My Recursive Function Returning Undefined in JavaScript?

 3 years ago
source link: https://typeofnan.dev/why-is-my-recursive-function-returning-undefined-in-javascript/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

TypeOfNaN

Why is My Recursive Function Returning Undefined in JavaScript?

Nick Scialli • November 13, 2020 • 🚀 1 minute read

stairwell

One common frustration when getting the hang of recursion is not understanding why your recursive function is returning undefined.

Often, this is because you’re not returning the next execution of your recursive function. I’ll show you what I mean.

Let’s say we’re writing a factorial function. Factorial is a mathematical operator where a number is multiplied by each lower number. For example, 4 factoral (written as 4!) is equivalent to 4 * 3 * 2 * 1 = 24.

We might write a recursive factorial function like this:

function factorial(num, result = 1) {
  if (num === 1) {
    return result;
  }
  factorial(num - 1, num * result);
}

console.log(factorial(4));
// undefined

But this should be 24! Why is it undefined? Well the answer is easier than we think: we need to return the next execution of the factorial function each time or else we’ll never get to the ultimate result!

function factorial(num, result = 1) {
  if (num === 1) {
    return result;
  }
  return factorial(num - 1, num * result);
}

console.log(factorial(4));
// 24

And that’s really it! The “secret” is to just make sure that, whatever path you go down in your function, make sure you’re returning something.


Nick Scialli

Nick Scialli is a software engineer at the U.S. Digital Service.

Subscribe to the mailing list!

If you like what I post here, please sign up to get updates and code insights in your inbox. I won't spam you and you can unsubscribe any time!

Enter your email

Powered by Buttondown.

© 2020, Built using Gatsby

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK