In this post, we will check an example of recursion with default function parameter of es6 JavaScript. Mind you, there is no benefit of doing the recursion this way. On the contrary, it is always better to write a more readable recursion algorithm within the body of the function. This is just for the sake of demonstration!
Fibonacci Example
Fibonacci generator is the most common recursive method. Here’s how its implementation looks like in JavaScript:
const fibonacci = (num) => {
if (num < 2) {
return num;
}
else {
return fibonacci(num - 1) + fibonacci(num - 2);
}
}
console.log(fibonacci(12)); // 144
You can observe the recursion happening when fibonacci
is called from within the body of fibonacci
. We can do the same recursion using default parameter as below:
const fibonacci = (num = 2, x = num >= 2 ? fibonacci(num - 1) + fibonacci(num - 2) : num) => x;
console.log(fibonacci(12)); // 144
Here note that x
is the second parameter in which we conditionally call the fibonacci
if num
is greater than equal to 2, else we assign num
to x
. This is the same fibonacci logic we perform in the body of the first example. But here the logic is performed before it even goes to the body of the function.
Again, there’s no conceivable reason why would you do that. So please don’t!
See also
- React JS Render Form With Dynamic Data From Backend API
- Exclude Yourself From Google Analytics Without Filtering IP Addresses or Using Extensions
- Find and Replace or Remove Multiple Instances of a Substring in JavaScript
- Remove or Replace a Substring in JavaScript String
- JavaScript Find Total Time Duration
- Get User Country and Region on Browser With JavaScript Only
- JavaScript Generate Your Own Random Number Without Math Random