Recursion... can be simple.
Hey guys,
Let’s talk about recursion.
Imagine you have a big task, and to solve it, you need to do a smaller version of the same task. Recursion is like telling a friend to do part of the job, and if that part also needs the same kind of help, they'll ask another friend, and so on.
Things to note: Recursion consists of two things, a base case and a recursive case.
Base case: a base case is like a safety net or a stopping point in a recursive function. It's a condition that, when met, tells the function to stop calling itself and return a result immediately.
Recursive case: The recursive case is the part of a recursive function where the function calls itself to solve a smaller instance of the same problem. In other words, it's like breaking down a big task into a smaller, more manageable task of the same type.
Let's look at a simple example in TypeScript - calculating the factorial of a number.
// Function to calculate factorial using recursion
function factorial(n: number): number {
// Base case: If the number is 0 or 1, the factorial is 1
if (n <= 1) {
return 1;
} else {
// Recursive case: n! = n * (n-1)!
return n * factorial(n - 1);
}
}
// Example usage
const num = 5;
const result = factorial(num);
// Print the result
console.log(`Factorial of ${num} is: ${result}`);
In simpler terms:
Now, let's imagine you want to know the factorial of 5.
Recursion is like breaking down a big problem into smaller pieces and solving each piece step by step, with each step asking the same question but with a smaller problem until you get to the simplest form.
Please subscribe to my newsletter if you like this kind of stuff! --> https://thenewdevs.substack.com/