-1

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;

}
Paolo
  • 15,233
  • 27
  • 70
  • 91
  • 2
    [`if(Number.isNaN(num))`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN)? Then you can throw an error, return `NaN`, or anything else. – evolutionxbox Sep 17 '22 at 09:10
  • @evolutionxbox That would miss an empty string. – gre_gor Sep 17 '22 at 09:36

2 Answers2

0

Assuming

  • you want to accept both numbers and strings representing a number (and convert them to number)

  • you want do avoid non integers and negative numbers since you're calcolating the factorial

    if( typeof( n ) !== 'string' &&
        ( typeof( n ) !== 'number' || Number.isNaN( n ) ) &&
        ( '' + n ).match(/^[0-9]+$/) === null ) {
        return null;
    }
    
Paolo
  • 15,233
  • 27
  • 70
  • 91
-2

Check the datatype of the variable by using the typeof function, and if its not a number, then throw a TypeError