loading...
Cover image for JavaScript Recursion Explained in 4 minutes

JavaScript Recursion Explained in 4 minutes

codenutt profile image Jared Originally published at Medium ・3 min read

Intro

Welcome to ByteSize Javascript where we chew on manageable chunks of code. Today we're going to be talking about recursion.

Recursion is one of those things that you see a lot when you're learning about JS. The question is, do you understand what it is? If you don't, I'm going to give two examples that will hopefully clear it up. If you do, check out my examples anyways! I'm sure you have some further insight you can share.

Video Version

If you learn well by watching, check out the video version of this article!

What is Recursion

Recursion is simply:

A function calling itself over and over again

It will call itself until one of two things happens:

  1. We reach the call stack limit.
  2. We define an exit value.

Simple Example

Let's start with a simple example. The goal of our function is to increment a number until we reach a limit...then stop. First, let's break it.

    function incrementer(ceiling,total) {
        total++
        return incrementer(ceiling, total)
    }
    incrementer(10,0)

That code will run until it you reach the call stack limit. Probably not what we want.

Now, let's add an "out" for a code.

    function incrementer(ceiling,total) {
        total++
        if (total === ceiling) {return total}
        return incrementer(ceiling, total)
    }
    incrementer(10,0)

Pretty simple. It doesn't do a lot for us, but it shows the principle that is:

Recursion is a function that calls itself.

Now let's take a look at a more robust example.

Robust Example

Let's say we want to find out:

What is the total of all the squared values up to a given value?

or in math terms:

1^2 + 2^2 + 3^2....n^2

To solve this, we can write a function that will do the following:

  1. check if we have reached our limiter
  2. square the value
  3. add it to the total
  4. decrement the value
  5. return to step 1

Check it out.

    // Our function takes in two values: 
    // our limiter (ceiling) and a total that we will return (inititally set at 0)
    function getSumSquares(ceiling, total = 0) {
        // check to see if we have reduced our ceiling to zero. If so...escape!
      if (ceiling === 0) {
        return total;
      }
        // if we still have more work to do, do the work
      total += ceiling ** 2;
        // call yourself, but reduce our ceiling by one.
      return getSumSquares(ceiling - 1, total);
    }
    getSumSquares(10)

The function is going to call itself until our condition is met, in this case, ceiling === 0, hence the name recursion.

Final Thoughts

Hopefully, that clears things up a bit. This is only the surface of what you can do with recursion. I've included some links below to provide more detail.

If you've got ideas for more JavaScript topics you'd like to discuss, shoot me a comment.

As always, happy coding!

Plugs

Book

I'm writing a book about graphic design and how it relates to software development! If you're interested, sign up here for updates.

https://digitalnutt.substack.com/p/coming-soon?r=34slo&utm_campaign=post&utm_medium=web&utm_source=copy

Music

I also write music! Check it out here:

https://open.spotify.com/artist/1o6CGTMPjk1C0IdK9jV2H1

https://www.youtube.com/channel/UCqxQspCPTcE_wH0KBE5J-aw

https://music.apple.com/us/artist/modulo/1499420471

Support

If you like this article and want to see more, the best way to do that is to subscribe/follow me on here! If you are feeling gracious, you can buy me a coffee!

Resources

This video is more specific to the event loop, but it covers what happens when the call stack is exceeded around the 7:00 mark.

Posted on by:

codenutt profile

Jared

@codenutt

L.A. based web developer slowly parsing through Stack Overflow. If you like hot web dev tips or stories about being a freelancer, check out my newsletter: https://codenutt.substack.com/p/coming-soon

Discussion

pic
Editor guide
 

Async,await, promise

 

Will do!

 

Recursion is no different in Javascript than any other language, so tagging/titling this "Javascript" is, in my opinion, clickbait.

 

Hi George! I'm not sure that's true for a couple of reasons.

  1. It is a common topic in JavaScript, particularly surrounding interviews.
  2. The examples are written in JavaScript.

Therefore the title delivers exactly what the article is: an explanation of recursion...in javascript...that you can read in about four minutes. I'm not sure it gets more straightforward than that.