Every JavaScript programmer grows up eventually. Here's the same function, factorial(6), as written at each stage of the journey.
// Newbie programmer
function factorial(x) {
if (x == 0) {
return 1;
} else {
return x * factorial(x - 1);
}
}
document.write(factorial(6));
// First year programmer, studied Java
class FactorialCalculator {
constructor(number) {
this.number = number;
}
getResult() {
var result = 1;
for (var i = 1; i <= this.number; i++) {
result = result * i;
}
return result;
}
}
console.log(new FactorialCalculator(6).getResult());
// Callback era
function factorial(n, callback) {
if (n <= 1) return setTimeout(function () { callback(1); }, 0);
factorial(n - 1, function (result) {
setTimeout(function () {
callback(n * result);
}, 0);
});
}
factorial(6, function (result) { console.log(result); });
// Discovered Promises
const factorial = (n) =>
n <= 1
? Promise.resolve(1)
: factorial(n - 1).then((result) => n * result);
factorial(6).then(console.log);
// async/await convert
async function factorial(n) {
let result = 1;
for (let i = 2; i <= n; i++) {
result *= await i; // just to be safe
}
return result;
}
factorial(6).then(console.log);
// ES6 one-liner
const f = (n) => (n ? n * f(n - 1) : 1);
console.log(f(6));
// Functional programmer
console.log(
Array.from({ length: 6 }, (_, i) => i + 1).reduce((a, b) => a * b, 1)
);
// Precision pedant
const f = (n) => (n ? n * f(n - 1n) : 1n);
console.log(String(f(6n)));
// npm developer
// $ npm install factorial-of
// added 1,284 packages, and audited 1,285 packages in 41s
// 87 vulnerabilities (12 low, 43 moderate, 32 high)
const factorialOf = require("factorial-of");
console.log(factorialOf(6));
// EXPERT PROGRAMMER
console.log(720);
See also: the evolution of a Python, Ruby, PHP, C or Perl programmer, and where this joke started, Fritz Ruehr's The Evolution of a Haskell Programmer (itself a riff on the old "Hello World" Evolution of a Programmer).