Replace Loops using Recursion(Basic JavaScripts)

However, notice that multiply(arr, n) == multiply(arr, n - 1) * arr[n - 1] . That means you can rewrite multiply in terms of itself and never need to use a loop.

Alright! pls someone explain me the math behind this, show me a formula/blueprint (if there is any, in order to detect any recursive possibility on a given algorithm)

or a better approach (Video/link =, where I can master my recursive logic)

thank you ! happy Friday all !


The multiply function multiplies the first n numbers in arr (at least I’m assuming that is what it does as you didn’t provide a link to the challenge and I’m too lazy to find it). So

multiply([4,5,6], 3)

will multiply 4 * 5 * 6.

Now if we reduce 3 to 2 (which is the n - 1 in this case):

multiply([4,5,6], 2)

will only multiply the first 2 numbers in the array

4 * 5

but then we multiply by the third number in the array (arr[n - 1]) which is 6:

(4 * 5) * 6

and so we get the same result.

In plain language, a function that multiplies all of the numbers in an array is the same as a function that multiplies all but the last number in an array and then we manually multiply the last number to the result.

1 Like

That’s Awesome ! And is there any math formula that can serve as a blue print for detecting if a function can be transformed in a recursive one ?

It’s been a long time since I dabbled in “serious” mathematics so I’m probably not qualified to answer this, but I don’t think there is a specific formula that will tell you this. Recursion is just an approach to solving a problem in which you break the problem down in to sub processes with the requirement that each sub process is just calling itself (the original function). There are categories of problems that lend themselves well to recursion but in reality, if you are doing front-end web development you will probably never use it.

But I understand why FCC teaches it. Learning recursion helps you learn how functions work. Also, it seems to be a common concept that people expect you to know even if you will never use it. The examples used in the FCC challenges aren’t something you would actually use in “real world” JS, but they are simple enough to explain the concept. So definitely make sure you understand what is going on in them but don’t go looking for places to use recursion because most likely there will be a better solution. But if you are interested you can google for good uses of recursion and believe it or not, there are some languages that require recursion to do any type of looping.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.