Some problems are more naturally solved using recursion. For example, a sequence like the Fibonacci sequence has a recursive definition. Each number in the sequence is the sum of the previous two numbers in the sequence. Problems that require you to build or traverse a tree-like data structure can also be solved with recursion. Training yourself to think recursively will give you a powerful skill to attack such problems.
In this tutorial, I will go through several recursive functions step by step to see how they work and show you techniques you can use to systematically define recursive functions.
A recursively defined function is a function that is defined in terms of a simpler version of itself. This is a simplified example:
function doA(n) { ... if (n > 0) { doA(n-1); } }
To understand how recursion works conceptually, we will look at an example that has nothing to do with code. Imagine you are responsible for answering phone calls at work. Since this is a busy company, your phone has multiple phone lines so you can juggle multiple calls at the same time. Each phone line has a button on the receiver, and when there is an incoming call, the button will blink. Today, when you arrive to work and turn the phone on, there are four lines blinking at once. So you get to work answering all of the calls.
You pick up line one and tell them, "Please hold." Then you pick up line two and put them on hold. Next, you pick up line three and put them on hold, and so on. Finally, when you are done with each call, you go back to the previous caller, finish that call, and hang up.
Each of the phone calls in this example is like a recursive call in a function. When you get a call, it is put on the call stack (in code speak). If you cannot complete a call right away, you put the call on hold. If you have a function call that can't be evaluated immediately, it stays on the call stack. When you are able to answer a call, it is picked up. When your code is able to evaluate a function call, it is popped off the stack. Keep this analogy in mind as you look over the following code examples.
All recursive functions need a base case so they will terminate. However, just adding a base case to our function does not prevent it from running infinitely. The function has to have a step to bring us closer to the base case. This is the recursive step. In the recursive step, the problem is reduced to a smaller version of the problem.
Suppose you have a function that will multiply all the numbers from 1
to n
. This is called the factorial function, and we write it as n!
. For example, 4!
, is 1 * 2 * 3 * 4 = 24
.
First, we determine the base case. Finding the base case can also be thought of as finding the case where the problem can be solved without recursion. In this case, it is when n
equals one.
At each step, you will subtract one from the current number. What is the recursive case? The recursive case is the function fact
called with the reduced number.
function fact(num) { if (num === 1) return 1; else return num * fact(--num); } fact(4); //24
This is what is happening at each step:
fact(4)
.fact(4)
on hold and go to fact(3)
.fact(3)
on hold and go to fact(2)
.fact(2)
on hold and go to fact(1)
.1
.fact(2)
and return 2 * fact(1)
is 2
.fact(3)
and return 3 * fact(2)
is 6
.fact(4)
and return 4 * fact(3)
is 24
.This is another way to view how the function is processing each call:
fact(4) 4 * fact(3) 4 * ( 3 * fact(2) ) 4 * ( 3 * ( 2 * fact(1) )) 4 * ( 3 * ( 2 * 1 ) ) 4 * ( 3 * 2 ) 4 * 6 24
The argument should change in the recursive case and bring you closer to the base case. This argument should be tested in the base case. In the previous example, because we are subtracting one in the recursive case, we test if the argument equals zero in our base case.
multiply(2,4)
will return 8. Write what happens at each step for multiply(2,4)
.Recurring on a list is similar to recurring on a number, except that instead of reducing the number at each step, we are reducing the list at each step until we get to an empty list.
Consider the sum function that takes a list as input and returns the sum of all of the elements in the list:
function sum(l) { if (l.length === 0) { return 0; } else { return l[0] + sum(l.slice(1)); } }
First, you check whether the array of numbers is empty. If it is, then you return 0
; otherwise, you return the first element of the array plus the sum
of all elements except the first. That is where the recursion comes in. Because sum
calls sum
when the array is longer than zero, the function is recursive. Here is a representation of what is happening at each step.
sum([1,2,3,4]) 1 + sum([2,3,4]) 1 + ( 2 + sum([3,4]) ) 1 + ( 2 + ( 3 + sum([4]) )) 1 + ( 2 + ( 3 + ( 4 + sum([]) ))) 1 + ( 2 + ( 3 + ( 4 + 0 ) )) 1 + ( 2 + ( 3 + 4 ) ) 1 + ( 2 + 7 ) 1 + 9 10
When recurring on a list, check if it is empty. Otherwise, do the recursive step on a reduced version of the list.
While recursion works here, loops can be faster and work better in cases like this. Rewrite this sum function so that it uses a loop to sum each item in the list instead of recursion.
In the last example, we were returning a number. But suppose we wanted to return a list. That would mean that instead of adding a number to our recursive step, we would need to add a list. Consider the remove
function, which takes an item and list as input and returns the list with the item removed. Only the first found instance will be removed.
function remove(item, l) { if (l.length === 0) { return []; } else if (item === l[0]) { return l.slice(1); } else { return [l[0], ...remove(item, l.slice(1))]; } } console.log(remove("c", ["a", "b", "c", "d"])); //[‘a’, ‘b’, ‘d’]
We will be checking if the first item in the list is equal to the item we want to remove. If it is, remove the first element from the list and return the new list. If the first item is not equal to the item we want to remove, we take the first element in the list and add it to the recursive step. The recursive step will contain the list with the first element removed.
We will keep removing elements until we reach our base case, which is an empty list. An empty list means we have traversed all the items in our list. What does remove('c', ['a', 'b', 'c', 'd'])
do?
["a", ...remove("c", ["b", "c", "d"])]; ["a", ...["b", ...remove("c", ["c", "d"])]]; ["a", ...["b", ...remove("c", ["d"])]]; ["a", ...["b", ...["d"]]]; ["a", ...["b", "d"]]; ["a", "b", "d"];
In a situation when we need to build a list, we take the first element and add it to the recursive part of our list.
remove
function so that it removes all occurrences of an item from a list. For example, remove("c", ["a", "b", "c", "d", "c"]
should return ["a", "b", "d"]
.remove
function to use JavaScript's built-in array method filter
.Tail recursion is a form of recursion that allows the compiler to perform tail call optimization (TCO) to prevent many of the performance pitfalls normal recursion has. Additionally, tail recursion solves the problem of having a maximum depth of function calls. However, you have to write your functions a certain way for this to work.
Tail recursion works with functions that call the recursive function at the end of the function. For example, here is the sum()
function refactored to use tail recursion:
function sum(l, n) { if (l.length === 0) { return n || 0; } else { n ??= 0; n += l[0]; return sum(l.slice(1), n); } }
As you can see, sum()
is the entire return value, so the runtime can safely discard the outer function and just return the result from the inner function. However, many people get tripped up by things like this:
function notTailRecursive(n) { ... return notTailRecursive(n)+1 }
You might think that this uses tail recursion, as the recursive function is called at the end. However, it does not. That is because JavaScript has to return to the outer function to add one. One way you could rewrite it is to pass the +1
inside the arguments, so then the inner function can do that computation.
Not all browsers currently support tail call optimizations, but it is in the ES standard, so we might see more support for it in the future. Additionally, it is often a good practice, as it usually isolates changes to the arguments of the function.
Refactor one of the example recursive functions in this post to be tail recursive.
There are three parts to a recursive function. The first is the base case, which is the terminating condition. The second is the step to get us closer to our base case. The third is the recursive step, where the function calls itself with the reduced input.
Recursion is like iteration. Any function that you can define recursively can also be defined using loops. Other things to consider when using recursion are recurring on nested lists and optimizing your recursive calls.
You can refactor recursive functions to be tail recursive, which can offer performance benefits.
A great resource to continue learning about recursion is the book The Little Schemer. It teaches you how to think recursively using a question-and-answer format.
This post has been updated with contributions from Jacob Jackson. Jacob is a web developer, technical writer, freelancer, and open-source contributor.
The Best Small Business Web Designs by DesignRush
/Create Modern Vue Apps Using Create-Vue and Vite
/How to Fix the “There Has Been a Critical Error in Your Website” Error in WordPress
How To Fix The “There Has Been A Critical Error in Your Website” Error in WordPress
/How Long Does It Take to Learn JavaScript?
/The Best Way to Deep Copy an Object in JavaScript
/Adding and Removing Elements From Arrays in JavaScript
/Create a JavaScript AJAX Post Request: With and Without jQuery
/5 Real-Life Uses for the JavaScript reduce() Method
/How to Enable or Disable a Button With JavaScript: jQuery vs. Vanilla
/How to Enable or Disable a Button With JavaScript: jQuery vs Vanilla
/Confirm Yes or No With JavaScript
/How to Change the URL in JavaScript: Redirecting
/15+ Best WordPress Twitter Widgets
/27 Best Tab and Accordion Widget Plugins for WordPress (Free & Premium)
/21 Best Tab and Accordion Widget Plugins for WordPress (Free & Premium)
/30 HTML Best Practices for Beginners
/31 Best WordPress Calendar Plugins and Widgets (With 5 Free Plugins)
/25 Ridiculously Impressive HTML5 Canvas Experiments
/How to Implement Email Verification for New Members
/How to Create a Simple Web-Based Chat Application
/30 Popular WordPress User Interface Elements
/Top 18 Best Practices for Writing Super Readable Code
/Best Affiliate WooCommerce Plugins Compared
/18 Best WordPress Star Rating Plugins
/10+ Best WordPress Twitter Widgets
/20+ Best WordPress Booking and Reservation Plugins
/Working With Tables in React: Part Two
/Best CSS Animations and Effects on CodeCanyon
/30 CSS Best Practices for Beginners
/How to Create a Custom WordPress Plugin From Scratch
/10 Best Responsive HTML5 Sliders for Images and Text… and 3 Free Options
/16 Best Tab and Accordion Widget Plugins for WordPress
/18 Best WordPress Membership Plugins and 5 Free Plugins
/25 Best WooCommerce Plugins for Products, Pricing, Payments and More
/10 Best WordPress Twitter Widgets
1 /12 Best Contact Form PHP Scripts for 2020
/20 Popular WordPress User Interface Elements
/10 Best WordPress Star Rating Plugins
/12 Best CSS Animations on CodeCanyon
/12 Best WordPress Booking and Reservation Plugins
/12 Elegant CSS Pricing Tables for Your Latest Web Project
/24 Best WordPress Form Plugins for 2020
/14 Best PHP Event Calendar and Booking Scripts
/Create a Blog for Each Category or Department in Your WooCommerce Store
/8 Best WordPress Booking and Reservation Plugins
/Best Exit Popups for WordPress Compared
/Best Exit Popups for WordPress Compared
/11 Best Tab & Accordion WordPress Widgets & Plugins
/12 Best Tab & Accordion WordPress Widgets & Plugins
1New Course: Practical React Fundamentals
/Preview Our New Course on Angular Material
/Build Your Own CAPTCHA and Contact Form in PHP
/Object-Oriented PHP With Classes and Objects
/Best Practices for ARIA Implementation
/Accessible Apps: Barriers to Access and Getting Started With Accessibility
/Dramatically Speed Up Your React Front-End App Using Lazy Loading
/15 Best Modern JavaScript Admin Templates for React, Angular, and Vue.js
/15 Best Modern JavaScript Admin Templates for React, Angular and Vue.js
/19 Best JavaScript Admin Templates for React, Angular, and Vue.js
/New Course: Build an App With JavaScript and the MEAN Stack
/Hands-on With ARIA: Accessibility Recipes for Web Apps
/10 Best WordPress Facebook Widgets
13 /Hands-on With ARIA: Accessibility for eCommerce
/New eBooks Available for Subscribers
/Hands-on With ARIA: Homepage Elements and Standard Navigation
/Site Accessibility: Getting Started With ARIA
/How Secure Are Your JavaScript Open-Source Dependencies?
/New Course: Secure Your WordPress Site With SSL
/Testing Components in React Using Jest and Enzyme
/Testing Components in React Using Jest: The Basics
/15 Best PHP Event Calendar and Booking Scripts
/Create Interactive Gradient Animations Using Granim.js
/How to Build Complex, Large-Scale Vue.js Apps With Vuex
1 /Examples of Dependency Injection in PHP With Symfony Components
/Set Up Routing in PHP Applications Using the Symfony Routing Component
1 /A Beginner’s Guide to Regular Expressions in JavaScript
/Introduction to Popmotion: Custom Animation Scrubber
/Introduction to Popmotion: Pointers and Physics
/New Course: Connect to a Database With Laravel’s Eloquent ORM
/How to Create a Custom Settings Panel in WooCommerce
/Building the DOM faster: speculative parsing, async, defer and preload
1 /20 Useful PHP Scripts Available on CodeCanyon
3 /How to Find and Fix Poor Page Load Times With Raygun
/Introduction to the Stimulus Framework
/Single-Page React Applications With the React-Router and React-Transition-Group Modules
12 Best Contact Form PHP Scripts
1 /Getting Started With the Mojs Animation Library: The ShapeSwirl and Stagger Modules
/Getting Started With the Mojs Animation Library: The Shape Module
/Getting Started With the Mojs Animation Library: The HTML Module
/Project Management Considerations for Your WordPress Project
/8 Things That Make Jest the Best React Testing Framework
/Creating an Image Editor Using CamanJS: Layers, Blend Modes, and Events
/New Short Course: Code a Front-End App With GraphQL and React
/Creating an Image Editor Using CamanJS: Applying Basic Filters
/Creating an Image Editor Using CamanJS: Creating Custom Filters and Blend Modes
/Modern Web Scraping With BeautifulSoup and Selenium
/Challenge: Create a To-Do List in React
1Deploy PHP Web Applications Using Laravel Forge
/Getting Started With the Mojs Animation Library: The Burst Module
/10 Things Men Can Do to Support Women in Tech
/A Gentle Introduction to Higher-Order Components in React: Best Practices
/Challenge: Build a React Component
/A Gentle Introduction to HOC in React: Learn by Example
/A Gentle Introduction to Higher-Order Components in React
/Creating Pretty Popup Messages Using SweetAlert2
/Creating Stylish and Responsive Progress Bars Using ProgressBar.js
/18 Best Contact Form PHP Scripts for 2022
/How to Make a Real-Time Sports Application Using Node.js
/Creating a Blogging App Using Angular & MongoDB: Delete Post
/Set Up an OAuth2 Server Using Passport in Laravel
/Creating a Blogging App Using Angular & MongoDB: Edit Post
/Creating a Blogging App Using Angular & MongoDB: Add Post
/Introduction to Mocking in Python
/Creating a Blogging App Using Angular & MongoDB: Show Post
/Creating a Blogging App Using Angular & MongoDB: Home
/Creating a Blogging App Using Angular & MongoDB: Login
/Creating Your First Angular App: Implement Routing
/Persisted WordPress Admin Notices: Part 4
/Creating Your First Angular App: Components, Part 2
/Persisted WordPress Admin Notices: Part 3
/Creating Your First Angular App: Components, Part 1
/How Laravel Broadcasting Works
/Persisted WordPress Admin Notices: Part 2
/Create Your First Angular App: Storing and Accessing Data
/Persisted WordPress Admin Notices: Part 1
/Error and Performance Monitoring for Web & Mobile Apps Using Raygun
/Using Luxon for Date and Time in JavaScript
7 /How to Create an Audio Oscillator With the Web Audio API
/How to Cache Using Redis in Django Applications
/20 Essential WordPress Utilities to Manage Your Site
/Introduction to API Calls With React and Axios
/Beginner’s Guide to Angular 4: HTTP
/Rapid Web Deployment for Laravel With GitHub, Linode, and RunCloud.io
/Beginners Guide to Angular 4: Routing
/Beginner’s Guide to Angular 4: Services
/Beginner’s Guide to Angular 4: Components
/Creating a Drop-Down Menu for Mobile Pages
/Introduction to Forms in Angular 4: Writing Custom Form Validators
/10 Best WordPress Booking & Reservation Plugins
/Getting Started With Redux: Connecting Redux With React
/Getting Started With Redux: Learn by Example
/Getting Started With Redux: Why Redux?
/How to Auto Update WordPress Salts
/How to Download Files in Python
/Eloquent Mutators and Accessors in Laravel
1 /10 Best HTML5 Sliders for Images and Text
/Site Authentication in Node.js: User Signup
/Creating a Task Manager App Using Ionic: Part 2
/Creating a Task Manager App Using Ionic: Part 1
/Introduction to Forms in Angular 4: Reactive Forms
/Introduction to Forms in Angular 4: Template-Driven Forms
/24 Essential WordPress Utilities to Manage Your Site
/25 Essential WordPress Utilities to Manage Your Site
/Get Rid of Bugs Quickly Using BugReplay
1 /Manipulating HTML5 Canvas Using Konva: Part 1, Getting Started
/10 Must-See Easy Digital Downloads Extensions for Your WordPress Site
/22 Best WordPress Booking and Reservation Plugins
/Understanding ExpressJS Routing
/15 Best WordPress Star Rating Plugins
/Creating Your First Angular App: Basics
/Inheritance and Extending Objects With JavaScript
/Introduction to the CSS Grid Layout With Examples
1Performant Animations Using KUTE.js: Part 5, Easing Functions and Attributes
Performant Animations Using KUTE.js: Part 4, Animating Text
/Performant Animations Using KUTE.js: Part 3, Animating SVG
/New Course: Code a Quiz App With Vue.js
/Performant Animations Using KUTE.js: Part 2, Animating CSS Properties
Performant Animations Using KUTE.js: Part 1, Getting Started
/10 Best Responsive HTML5 Sliders for Images and Text (Plus 3 Free Options)
/Single-Page Applications With ngRoute and ngAnimate in AngularJS
/Deferring Tasks in Laravel Using Queues
/Site Authentication in Node.js: User Signup and Login
/Working With Tables in React, Part Two
/Working With Tables in React, Part One
/How to Set Up a Scalable, E-Commerce-Ready WordPress Site Using ClusterCS
/New Course on WordPress Conditional Tags
/TypeScript for Beginners, Part 5: Generics
/Building With Vue.js 2 and Firebase
6 /Best Unique Bootstrap JavaScript Plugins
/Essential JavaScript Libraries and Frameworks You Should Know About
/Vue.js Crash Course: Create a Simple Blog Using Vue.js
/Build a React App With a Laravel RESTful Back End: Part 1, Laravel 5.5 API
/API Authentication With Node.js
/Beginner’s Guide to Angular: HTTP
/Beginner’s Guide to Angular: Routing
/Beginners Guide to Angular: Routing
/Beginner’s Guide to Angular: Services
/Beginner’s Guide to Angular: Components
/How to Create a Custom Authentication Guard in Laravel
/Learn Computer Science With JavaScript: Part 3, Loops
/Build Web Applications Using Node.js
/Learn Computer Science With JavaScript: Part 4, Functions
/Learn Computer Science With JavaScript: Part 2, Conditionals
/Create Interactive Charts Using Plotly.js, Part 5: Pie and Gauge Charts
/Create Interactive Charts Using Plotly.js, Part 4: Bubble and Dot Charts
Create Interactive Charts Using Plotly.js, Part 3: Bar Charts
/Awesome JavaScript Libraries and Frameworks You Should Know About
/Create Interactive Charts Using Plotly.js, Part 2: Line Charts
/Bulk Import a CSV File Into MongoDB Using Mongoose With Node.js
/Build a To-Do API With Node, Express, and MongoDB
/Getting Started With End-to-End Testing in Angular Using Protractor
/TypeScript for Beginners, Part 4: Classes
/Object-Oriented Programming With JavaScript
/10 Best Affiliate WooCommerce Plugins Compared
/Stateful vs. Stateless Functional Components in React
/Make Your JavaScript Code Robust With Flow
/Build a To-Do API With Node and Restify
/Testing Components in Angular Using Jasmine: Part 2, Services
/Testing Components in Angular Using Jasmine: Part 1
/Creating a Blogging App Using React, Part 6: Tags
/React Crash Course for Beginners, Part 3
/React Crash Course for Beginners, Part 2
/React Crash Course for Beginners, Part 1
/Set Up a React Environment, Part 4
1 /Set Up a React Environment, Part 3
/New Course: Get Started With Phoenix
/Set Up a React Environment, Part 2
/Set Up a React Environment, Part 1
/Command Line Basics and Useful Tricks With the Terminal
/How to Create a Real-Time Feed Using Phoenix and React
/Build a React App With a Laravel Back End: Part 2, React
/Build a React App With a Laravel RESTful Back End: Part 1, Laravel 9 API
/Creating a Blogging App Using React, Part 5: Profile Page
/Pagination in CodeIgniter: The Complete Guide
/JavaScript-Based Animations Using Anime.js, Part 4: Callbacks, Easings, and SVG
/JavaScript-Based Animations Using Anime.js, Part 3: Values, Timeline, and Playback
/Learn to Code With JavaScript: Part 1, The Basics
/10 Elegant CSS Pricing Tables for Your Latest Web Project
/Getting Started With the Flux Architecture in React
/Getting Started With Matter.js: The Composites and Composite Modules
Getting Started With Matter.js: The Engine and World Modules
/10 More Popular HTML5 Projects for You to Use and Study
/Understand the Basics of Laravel Middleware
/Iterating Fast With Django & Heroku
/Creating a Blogging App Using React, Part 4: Update & Delete Posts
/Creating a jQuery Plugin for Long Shadow Design
/How to Register & Use Laravel Service Providers
2 /Unit Testing in React: Shallow vs. Static Testing
/Creating a Blogging App Using React, Part 3: Add & Display Post
/Creating a Blogging App Using React, Part 2: User Sign-Up
20 /Creating a Blogging App Using React, Part 1: User Sign-In
/Creating a Grocery List Manager Using Angular, Part 2: Managing Items
/9 Elegant CSS Pricing Tables for Your Latest Web Project
/Dynamic Page Templates in WordPress, Part 3
/Angular vs. React: 7 Key Features Compared
/Creating a Grocery List Manager Using Angular, Part 1: Add & Display Items
New eBooks Available for Subscribers in June 2017
/Create Interactive Charts Using Plotly.js, Part 1: Getting Started
/The 5 Best IDEs for WordPress Development (And Why)
/33 Popular WordPress User Interface Elements
/New Course: How to Hack Your Own App
/How to Install Yii on Windows or a Mac
/What Is a JavaScript Operator?
/How to Register and Use Laravel Service Providers
/
waly Good blog post. I absolutely love this…