Someone new talking about Recursion

drewbxkewb

dREWbxKewb

Posted on November 30, 2022

Someone new talking about Recursion

Recursion is a very interesting topic, as it is creating loops in code using functions. The more advanced explanation of recursion is a function that returns itself unless it hits a stop return.

function add(array, output=0){
  if(array.length === 0){
    return output;   // Key 1
  }
  output += array[0];
  return add(array.slice(1), output);  // Key 2
}
Enter fullscreen mode Exit fullscreen mode

Key 1: The Stop
This chunk of the code is the stopping mechanism. This insures that the functions stops at a certain point, as to not create an infinite loop.

if(array.length === 0)

This part is the check and usually results to true or false. If the check results in true, then it executes this line.

return output;

This output is indicated by the output in the function build, but we will get to that soon.

Key 2: The Loop
This section of the code is the looping mechanism. Basically the code does something, then returns the function call as its final act. In the case for the example we look at what is being done first before the loop occurs.

output += array[0]

Output is being added to by the value at 0 in the array.

return add(array.slice(1), output)

This is the meat of the loop. The return is pushing out the function call, but as you can see there are some changes that happen to are parameters as it goes though.

array.slice(1)

Using the slice method, we are removing the number at the zero index of array and making the one index our new zero. This is important, as without that bit, you will create another infinite loop. The last thing is the output. If you started with an output in the function creation, you need to carry it over to the next call as it has been modified in the code either.

Not necessary to the explanation, but the output can be anything you assign it to to help make the recursion simple.

While recursions are simple to write, they take a lot more computing power to execute than a simple loop does. That doesn't mean they aren't practical however. Recursions are simple to design and loop just as well as a for loop can.

💖 💪 🙅 🚩
drewbxkewb
dREWbxKewb

Posted on November 30, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related