What Is Javascript Recursion? π
In this tutorial, you will learn about recursion in JavaScript with the help of examples

Web Developer +15 years, Bug Bounty Hunter +5 years, Email: contact@therceman.dev
Search for a command to run...
In this tutorial, you will learn about recursion in JavaScript with the help of examples

Web Developer +15 years, Bug Bounty Hunter +5 years, Email: contact@therceman.dev
No comments yet. Be the first to comment.
Bug Bounty Writeup: How I Found XSS in 15 Minutes

Short & Basic Intro

Web Address Example Scheme and its Mandatory Components Explained

WEBP is a new image compression technology that creates smaller file sizes without compromising on quality

Recursion is a mathematical concept that has many applications in daily life.
As website developers, we encounter recursive functions every day.
This tutorial will explore the pattern of problems, which can be solved using recursion.
function recurse() {
// 2nd call to itself
recurse();
}
// 1st call
recurse();
Each recursive function must have a base case (also called termination condition), where it stops the recursion, or else it will continue calling itself indefinitely.
function recurse() {
if (terminate)
return; // stop calling recurse();
// continue recurse() if there is no termination
recurse();
}
recurse();
The recursion technique looks similar to the while loop.
Imagine that you need to multiply the desired number by themselves X times.
For example: 2 * 2 * 2 = 8
function multiply(n, x) {
let i = 0;
let res = 1;
while (i < x) {
res = res * n;
i++;
}
return res;
}
How does the loop works?
multiply(2,3)
1. i = 0, res = (1) * 2 // 0 < 3 continue ...
2. i = 1; res = (2) * 2 // 1 < 3 continue ...
3. i = 2; res = (2 * 2) * 2 // 2 < 3 continue ...
4. i = 3; res = (2 * 2 * 2) // 3 < 3 (false) break and return 8
function multiply(n, x) {
return x > 1 ? n * multiply(n, x - 1) : n;
}
How does the recursion works?
Let's imagine we need to URL encode the string <html> 5 times
The output should look like this:
%252525253Chtml%252525253E
function encode(str, n) {
let i = 0;
while (i < n) {
str = encodeURI(str)
i++;
}
return str;
}
function encode(str, n) {
return n ? encode(encodeURI(str), n - 1) : str;
}
Let's imagine we need to decode an URL that has been encoded multiple times
For example let's take previous URL encoded string:
%252525253Chtml%252525253E
The output result will be: <html>
function decode(str) {
while (str !== decodeURI(str)) {
str = decodeURI(str)
}
return str;
}
function decode(str) {
return str !== decodeURI(str) ? decode(decodeURI(str)) : str;
}
Imagine you need to replace bad tags, like <script>, from your HTML code
1st case: hello<script> world<script>
2nd case: hello<sc<script>ript>world
With the first case, we can easily do something like this:
let html_code = 'hello<script> world<script>';
let output = html_code.replaceAll('<script>','');
// output: hello world
But.. with the second case it will fail:
let html_code = 'hello<sc<script>ript> world';
let output = html_code.replaceAll('<script>','');
// output: hello<script> world
Here is where Recursion comes to the rescue
function clean_html(html, bad_tag) {
let cleaned_html = html.replaceAll(bad_tag, '');
return html === cleaned_html ? html : clean_html(cleaned_html, bad_tag)
}
clean_html('hello<sc<script>ript> world', '<script>');
// output: hello world
In this example, we need to find category by ID in a deeply nested array
Our target is a category with ID number 5
let the_category_list = [
{"id" : 1, "name" : "fruits", "child_list" : [
{"id" : 2, "name" : "apple", "child_list" : [
{"id" : 4, "name" : "red apple", "child_list" : []},
{"id" : 5, "name" : "green apple", "child_list" : []}
]},
{"id" : 3, "name" : "banana", "child_list" : []}
]}
]
function find_category_by_id(id, category_list) {
let found_category = false;
category_list.forEach(category => {
if (category.id === id)
found_category = category;
if (found_category === false && category.child_list.length)
found_category = find_category_by_id(id, category.child_list)
});
return (found_category) ? found_category : false;
}
find_category_by_id(5, the_category_list)
// Output: {id: 5, name: "green apple", child_list: Array(0)}
This example will show you how to write a factorial program in javascript using recursion
Let's imagine we need a factorial of 5: 1 * 2 * 3 * 4 * 5 = 120
function factorial(x) {
return x ? x * factorial(x - 1) : 1;
}
In this example, you will learn how to write a program to print Fibonacci series using recursion
Fibonacci sequence is written as: 0, 1, 1, 2, 3, 5, 8, 13, 21, β¦
function fibonacci(num) {
return num < 2 ? num : fibonacci(num - 1) + fibonacci(num - 2);
}
function fibonacci_printer(numberOfTerms) {
let out = [];
for(let i = 0; i < numberOfTerms; i++) {
out.push(fibonacci(i));
}
console.log(out.join(', '));
}
To use this program, you need to call fibonacci_printer(5) and the output will be:
0, 1, 1, 2, 3
Thanks for reading!
More examples will be added later.
Follow me on Twitter - twitter.com/therceman