Recursion is the concept that a function can be expressed in terms of itself. To help understand this, start by thinking about the following task: multiply the first <code>n</code> elements of an array to create the product of those elements. Using a <code>for</code> loop, you could do this:
However, notice that <code>multiply(arr, n) == multiply(arr, n - 1) * arr[n - 1]</code>. That means you can rewrite <code>multiply</code> in terms of itself and never need to use a loop.
The recursive version of <code>multiply</code> breaks down like this. In the <dfn>base case</dfn>, where <code>n <= 0</code>, it returns 1. For larger values of <code>n</code>, it calls itself, but with <code>n - 1</code>. That function call is evaluated in the same way, calling <code>multiply</code> again until <code>n <= 0</code>. At this point, all the functions can return and the original <code>multiply</code> returns the answer.
<strong>Note:</strong> Recursive functions must have a base case when they return without calling the function again (in this example, when <code>n <= 0</code>), otherwise they can never finish executing.
- text: Your code should not rely on any kind of loops (<code>for</code> or <code>while</code> or higher order functions such as <code>forEach</code>, <code>map</code>, <code>filter</code>, or <code>reduce</code>.).