In JavaScript, functions are first-class values, which means you can assign them to variables, pass them as arguments to other functions, and even nest them inside other functions. This leads to concise and expressive code.
Here's an example of a simple recursive function that calculates the factorial of a given number in JavaScript:
1const factorial = n => n === 0 ? 1 : n * factorial(n - 1);
2
3console.log(factorial(5)); // Output: 120
4
Now, let's try to write an equivalent code snippet in ANSI-C with similar functionality:
1#include <stdio.h>
2#define MAX_RECURSION_DEPTH 1000
3int factorial(int n) {
4 if (n == 0)
5 return 1;
6 else {
7 int result;
8 result = factorial(--n);
9 if (++depth > MAX_RECURSION_DEPTH)
10 while(1){} // Recursion stack overflow
11 return n * result;
12 }
13}
14int main() {
15 int i, result;
16 int n = 5;
17 int depth = 0;
18
19 result = factorial(n);
20 printf("Factorial of %d is: %d\n", n, result);
21 return 0;
22}
As you can see, the ANSI-C code becomes more verbose and has several disadvantages compared to JavaScript:
- Need to define a maximum recursion depth using a constant or an array index, which can lead to hardcoded limits and potential stack overflow issues.
- The use of preprocessor directives (#define) for defining functions and macros can make the code less readable and harder to understand.
- The lack of closures in ANSI-C requires using static variables or passing arguments as arguments to nested functions, making the code more verbose and less concise.