This example of a recursive function (below) is taken from a Codecademy exercise on understanding parameters.
Something that can be difficult as you climb any learning curve is synthesising all the new information you’re receiving into something that makes sense. It’s not always obvious how it all fits together, and sometimes you just hit up against something that totally befuddles you. I’m looking back at some of my little hurdles so far, starting with this:
1 2 3 4 5 6 7 8 9 10 11 | |
The problem: The console.log was displaying the expected result, but I didn’t understand why. Partly this was down to my incomplete grasp of basic maths. I understood the exponent tells you how many times to multiply the base number by itself:
2² = 2 x 2 = 4
2³ = 2 x 2 x 2 = 8
Then I assumed a base number with no exponent showing, e.g., 2, has an exponent of 0, because, well, you multiply the base number by itself zero times, but, and I’m guessing a lot of you are a step ahead of me, I was wrong:
2⁰ != 2
The exponent in fact tells you how many times to use the base number in an equation:
Don’t use it: 2⁰ = 1
Use it once: 2¹ = 1 x 2 = 2
Use it twice: 2² = 1 x 2 x 2 = 4 …
Going back to our power function, an if statement checks the condition exponent === 0. If this statement is true, we run the if-block: return 1 and exit the function.
Otherwise we run the else-block: return the base number multiplied by the product of calling the power function with new parameters (base, exponent -1).
This is an example of recursion (a function that calls itself): You keep returning the base number and calling the function until exponent === 0, at which point you run the if-block and exit the function.
Here’s the code again:
1 2 3 4 5 6 7 8 9 | |
The console.log returns a value of true. I had to break it down before I truly got it:
exponent === 3:return 2and multiply it by the product of calling the function with new parameters(2, 2)exponent === 2:return 2and multiply it by the product of calling the function with new parameters(2, 1)exponent === 1:return 2and multiply it by the product of calling the function with new parameters(2, 0)Exponent = 0:return 1and exit the function
So there we have it: 2 x 2 x 2 x 1 = 8 = Don’t I feel like a numpty now!

27 Aug. 2012: For an updated understanding see Recursion Revisited: The Stack.
