Skip to content
View in the app

A better way to browse. Learn more.

Web Designer Forum

A full-screen app on your home screen with push notifications, badges and more.

To install this app on iOS and iPadOS
  1. Tap the Share icon in Safari
  2. Scroll the menu and tap Add to Home Screen.
  3. Tap Add in the top-right corner.
To install this app on Android
  1. Tap the 3-dot menu (⋮) in the top-right corner of the browser.
  2. Tap Add to Home screen or Install app.
  3. Confirm by tapping Install.

Javascript help!

Featured Replies

I've recently started to learn javascript but I'm a bit stuck on understanding the flow of the following example of recursion:

 

/*

function power(base, exponent) {
if (exponent == 0)
return 1;
else
return base * power(base, exponent - 1);
}

console.log(power(2, 3));
// → 8

*/

 

Any help appreciated.

Which part are you stuck on? In this example, the base case has the job of stopping the function, that's your IF statement at the top, and the recursive case is the bit wrapped inside ELSE that calls itself. If you're doing an online tutorial, I recommend sticking with it, there's more to recursion, and it might start to make sense with some more examples. You'll also likely see an example at some point adding an iterator like a for loop.

If that's the code they are providing then you should look to learn from a different resource as a snippet even as small as that is littered with smells.

 

1. using == in the if statement, should be using === to avoid type coercion.

2. no curly braces around the statements inside of the if blocks. Always use {} to wrap these blocks otherwise an unwitting maintainer or yourself down the line might add some more statements that don't get reached and it leads to confusion.

3. No need for the else block as the if immediately returns when true.

 

better written as

function power(base, exponent) {
  if (exponent === 0) {
    return 1;
  }

  return base * power(base, exponent - 1);
}

This function can be reduced further with a ternary if you prefer their conciseness.

function power(base, exponent) {
  return exponent === 0
    ? 1
    : base * power(base, exponent - 1);
}

That might make it a bit easier to read now. Like Jack said there's a lot more to recursion than this example. It's important to know about how the call stack works.

Essentially when the function first gets called it pushes it to the stack. If that function calls itself again the second instance gets pushed to the top of the stack and so on - building up the stack.

In this example the function will call itself until the base case returns true. It can be confusing at first if you don't know how the call stack works in this instance. Many might assume that on the final call to power() when the base case is matched that the whole thing will return "1".
That is not the case as this the base case will return true only on the final function on the stack, so it will return 1 to the function that called it - the next function on the stack.

function power(2, 1) {
  return exponent === 0
    ? 1
    : 2 * 1); // "1" coming from the return value from the last instance of power() that was popped from the stack
}

//This can be shortened to

function power(2, 1) {
  return exponent === 0
    ? 1
    : 2);
}

// in the case above the exponent is "1" so the function will return "2" as it is popped off the stack.


// The next function on the stack:
function power(2, 2) {
return exponent === 0
? 1
: 2 * 2); // "2" coming from the return value from the last instance of power() that was popped from the stack
}

//This can be shortened to

function power(2, 2) {
return exponent === 0
? 1
: 4);
}

// in the case above the exponent is "2" so the function will return "4" as it is popped off the stack.


// The next function on the stack:
function power(2, 3) {
return exponent === 0
? 1
: 2 * 4); // "4" coming from the return value from the last instance of power() that was popped from the stack
}

//This can be shortened to

function power(2, 3) {
return exponent === 0
? 1
: ;
}

 

Then the function above gets popped off the stack and so on until the final function call has been popped off and the return value of that is the result - in this case "8".

Typically a loop would be a nicer approach to solve this problem until the browsers implement proper tail call optimisation.
Or in this specific case the Math object has a bunch of methods for performing common mathematical operations.

Math.pow(2, 3); // 8

Recursion is most useful for traversing tree structures. It might be worth spending some time learning about these kinds of data structures if you want to learn more about recursion. Navigating a tree using loops becomes very cumbersome very quickly whereas with recursion you can traverse with a small amount of code.

Edited by rbrtsmith

  • Author

Hey guys, that's impressive!
I didn't expect such detailed responses.

Thanks for taking the time, I'll look over the details after work tonight.

 

Thanks again.

Create an account or sign in to comment

Account

Navigation

Search

Search

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.