Recursion in JavaScript
This example demonstrates recursive functions in JavaScript. Here’s a classic implementation of factorial using recursion.
To run this code, you can save it in a file named recursion.js
and execute it using Node.js:
In this JavaScript version:
We define a
fact
function that calculates the factorial of a number recursively.We then define a
fib
function as a constant, which calculates the Fibonacci number for a given index using recursion.Both functions are called with the argument 7, and their results are printed to the console.
The main differences from the original example are:
- JavaScript doesn’t require explicit type declarations.
- In JavaScript, we can define the recursive closure (
fib
) directly without needing to declare its type beforehand. - We use
console.log()
instead offmt.Println()
for output.
This example showcases how JavaScript supports recursive functions, both as named functions and as anonymous function expressions (closures).