When we talked about function, I mentioned you can extract some portion of code, give it a name, and call it later.
For example say you have this code
const x = 1
const result = x * 2
console.log(result)
const anotherResult = 10 * 2
console.log(anotherResult)
You can take the x * 2
operation, assign it to a doubleNumber
function:
function doubleNumber(num) {
return num * 2
}
and now the code can be rewritten using
const x = 1
const result = doubleNumber(x)
console.log(result)
const anotherResult = doubleNumber(10)
console.log(anotherResult)
One interesting part is that functions can call themselves.
You might think: why? Or, why should I know this?
This has very practical implications, and can be especially useful when creating an algorithm, or a complex calculation.
The classic example is the factorial calculation. Given a number, the result should be the it, multiplied by the number - 1, multiplied by the number - 2, until you reach the number 1.
It’s hard to see how to create a general purpose function to solve this, until you add recursion to the mix:
function calculateFactorial(number) {
if (number === 1) {
return 1
}
return number * calculateFactorial(number - 1)
}