I was writing a factorial function and I wanted to add a logic that returns null
if the user puts anything into the argument instead of numbers like symbols (@#!) or letters (s,z).
how can I recognize them and immediately stop my program and return null
?
I know some ways but they will make my code really ugly and hard to read and long.
function factorial(n){
let num = Number(n);
// make num - 1 each time and push it into the list
let miniaturizedNum = [];
for (num; num > 0; num--){
miniaturizedNum.push(num);
}
// Multiply the finalresult with the numbers in the list
// and finalresault is 1 because zero multiplied by anything becomes zero
let finalResault = 1;
for (let i = 0; i < miniaturizedNum.length; i++){
finalResault *= miniaturizedNum[i];
}
return finalResault;
}