Using Recursion

Intro to Recursion in JavaScript

As I strengthen my JavaScript fundamentals, I am constantly being introduced to different tools and ways to think as a JavaScript developer. I recently have been introduced to recursion and more specifically recursive functions.

On a very basic level, using recursion in programming means the calling a function within itself until a certain condition is reached.

A recursive function must have a condition to stop calling itself. Otherwise, the function is called indefinitely. Once the condition is met, the function stops calling itself. This condition is generally called a base condition.To prevent infinite recursion, you can use and if else statement where one part of the function makes the recursive call, and the other doesn’t. Down below is a very basic example of how recursion works.

function IamRecursion() {
if(base condition) { <====== base condition needed to end recusion
IamRecursion(); <==== function calling itself
}
else {
// stop calling recursion()
}
}
IamRecursion();

Recursion is helpful to know for technical interviews , but it has some very real world programming uses. A few of these real world situations include delaying timers, for example if you wanted to execute a function multiple times after a set period of time, recursion can be an excellent option. Recursion can also be extremely helpful to use while iterating through a big set of data such as an array and finding a specific element, recursion can make the search more efficient . Recursion also allows for programmers to write DRY code as well as much cleaner code easier for fellow programmers to read.

Happy Coding!

--

--

--

Full-Stack Software Engineer / New York City / www.danielcreyes.dev

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Add Correlation ID in Node.JS Applications

How to convert an Excel XLSX to a PNG Array in Node.JS

Balance of Forces: JQuery vs hand-rolled

Social Media MetaTag Generator

When is it okay to Unit Test private variables and functions in JavaScript?

Collections of The Shiboshis

What is a debounce function and how do I use it in React?

Pragmatic Front-End Testing Strategies (3)

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Daniel C Reyes

Daniel C Reyes

Full-Stack Software Engineer / New York City / www.danielcreyes.dev

More from Medium

JavaScript Functions — Part 2…

JavaScript Array.map(): Read all about it!

Introduction to JavaScript

Deep Dive into Data structures using Javascript — Circular Doubly Linked List — Şahin Arslan