Sitemap
codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Follow publication

Learn and Understand Recursion in JavaScript

6 min readJul 6, 2017

--

recursion — image via unsplash.com

What is Recursion?

function factorial(x) {
if (x < 0) return;
if (x === 0) return 1;
return x * factorial(x - 1);
}
factorial(3);
// 6

The three key features of recursion

A Termination Condition

A Base Case

The Recursion

All Three Together

function factorial(x) {
// TERMINATION
if (x < 0) return;
// BASE
if (x === 0) return 1;
// RECURSION
return x * factorial(x - 1);
}
factorial(3);
// 6

Factorial Function Flow

factorial(3);
return 3 * factorial(2);
return 2 * factorial(1);
return 1 * factorial(0);
if (x === 0) return 1;
return 1 * 1 * 2 * 3
// 6

Did you follow that? Here is the same explanation structured differently:

factorial(3) returns 3 * factorial(2)
factorial(2) returns 2 * factorial(1)
factorial(1) returns 1 * factorial(0)
factorial(0) returns 1
// Now that we've hit our base case, our function will return in order from inner to outer:factorial(0) returns 1 => 1
factorial(1) returns 1 * factorial(0) => 1 * 1
factorial(2) returns 2 * factorial(1) => 2 * 1 * 1
factorial(3) returns 3 * factorial(2) => 3 * 2 * 1 * 1
// 3 * 2 * 1 * 1 = 6

Lets look at a second example

function revStr(str){
if (str === '') return '';
return revStr(str.substr(1)) + str[0];
}
revStr('cat');
// tac

Let’s break it down line by line

revStr('cat');
return revStr(str.substr(1)) + str[0];// SAME AS
return revStr('at') + 'c'
return revStr(str.substr(1)) + str[0];// SAME AS
return revStr('t') + 'a'
return revStr(str.substr(1)) + str[0];// SAME AS
return revStr('') + 't'
if (str === '') return '';
return ‘’ + ‘t’ + ‘a’ + ‘c’
// tac

Break it down even more

revStr('cat')  returns revStr('at') + 'c'revStr('at')   returns revStr('t') +  'a'revStr('t')    returns revStr('') +   't'revStr('')     returns               ''
revStr('')     returns                ''  => ''revStr('t')    returns revStr('') +   't' => '' + 't'revStr('at')   returns revStr('t') +  'a' => '' + 't' + 'a'revStr('cat')  returns revStr('at') + 'c' => '' + 't' + 'a' + 'c'// tac

Want More Advanced JavaScript?

Closing Notes

If this post was helpful, please click the clap 👏button below a few times to show your support! ⬇⬇ Also, check out my recent articles:

--

--

codeburst
codeburst

Published in codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Brandon Morelli
Brandon Morelli

Written by Brandon Morelli

Creator of @codeburstio — Frequently posting web development tutorials & articles. Follow me on Twitter too: @BrandonMorelli

Responses (29)