Recognize anything which is not a number and return null

Viewed 43

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;

}
2 Answers

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;
    }
    

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

Related