Skip to content

Instantly share code, notes, and snippets.

@edmangimelli
Last active April 3, 2019 20:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save edmangimelli/579fd11420b0ee5943adab5cc10e55e6 to your computer and use it in GitHub Desktop.
Save edmangimelli/579fd11420b0ee5943adab5cc10e55e6 to your computer and use it in GitHub Desktop.

I've recently started wrapping the inside of my recursive functions to protect them against renaming/passing:

For instance, say you have:

let factorial = n => {
  if (n == 1) return 1;
  return n * factorial(n-1);
}

What if this happens:

let recursiveFunc = factorial;

factorial = 1;

recursiveFunc(5)  // doesn't work

recursiveFunc refers to the original function, but, because the original function calls factorial, which got redefined, it no longer works.

Even if you think this specific scenario is unlikely, passing around functions is pretty commonplace in JS-land, and, who knows, maybe the function got imported with a different name, or you received the function as a member of an object.

A solution. Do the recursion inside the function:

let factorial = n => {
  const factorial = n => {
    if (n == 1) return 1;
    return n * factorial(n-1);
  }
  return factorial(n);
}

let recursiveFunc = factorial;

factorial = 1;

recursiveFunc(5)  // works!
@sethetter
Copy link

FWIW, this is often how things are done in Haskell when recursion is needed (quite often).

@Mottie
Copy link

Mottie commented Apr 3, 2019

This is why you use const instead of let.

@edmangimelli
Copy link
Author

This is why you use const instead of let.

That solves the example, but the example isn't how I would expect it to happen in the wild.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment