I have a recursive function that I put together for a challenge which calculates factorials by building an array and then reducing the values of the array in order to return the expected value.
When I run the function, I’m able to log my expected value but return ‘undefined’. Any explanation as to why this occurs would be greatly appreciated.
const sumOf = (thisArray) => thisArray.reduce((a,b)=> a + b)
let factorArray = [1, 1]
function factorial(endAtNumber) {
if (endAtNumber === 1) return 1;
if (endAtNumber === factorArray.length) {
console.log(endAtNumber === factorArray.length) // logs true
console.log(sumOf(factorArray)) // logs expected value (e.g factorial(5) = 120)
return sumOf(factorArray) // returns undefined
}
else {
let pushValue = sumOf(factorArray)
let factorArrayLen = factorArray.length
factorArray = []
for (let i = 0; i <= factorArrayLen; i++) {
factorArray.push(pushValue)
}
}
factorial(endAtNumber)
}
console.log(factorial(5))
// expecting 120; returns undefined
