# Basic JavaScript: Replace Loops using Recursion

Tell us what’s happening:
First, I do not understand how the demonstrated for-loop code works. On top of that, I do not understand how the recursion code works and why it is a better alternative to the for-loop method. Please try to explain it to me in the simplest possible way

##Below is the problem

## Basic JavaScript: Replace Loops using Recursion

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 elements from `0` to `n` inclusive in an array to create the product of those elements. Using a `for` loop, you could do this:

``````  function multiply(arr, n) {
var product = arr[0];
for (var i = 1; i <= n; i++) {
product *= arr[i];
}
return product;
}
``````

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

``````  function multiply(arr, n) {
if (n <= 0) {
return arr[0];
} else {
return multiply(arr, n - 1) * arr[n];
}
}
``````

``````function sum(arr, n) {
// Only change code below this line

// Only change code above this line
}
``````

User Agent is: `Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36`.

Challenge: Replace Loops using Recursion

if you do not understand for loops maybe you need to review how loops work. go back to see the challenges about loops.

it is not better, but it is a different way of doing things that you need to understand because you can find used around.

Recursion loops are often very elegant ways to solve a problem, and when identified may simplify the problem as well, avoiding spaghetti code.

It’s just a different way to solve. Even though I understand what recursion is, I still have a hard time writing them for some reason bc they kind of “feel” wrong from a coding perspective like they are too simple and therefore something is missing.

You can use recursion for problems like Fibonacci sequence, towers of Hanoi, least common multiplier, fractal generation, investment or amortization calculations , etc.

Anything where you do the same operation in a prior iteration of the solution can be recursed.

This is how for loop works https://www.programiz.com/c-programming/c-for-loop
Now try to relate it with the above problem given.

This is how recursion works https://www.youtube.com/watch?v=HEjmH9wKiMo&list=PLEbnTDJUr_IeHYw_sfBOJ6gk5pie0yP-0&index=6

Start watching from 9:27 to 18:27 . You will understand how recursive program works using stack and tree.

Another great video for recursion: https://www.youtube.com/watch?v=Mv9NEXX1VHc 3:46 to end of video

Watch both video you will understand how it works.

2 Likes