Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I make JS function recognize input that is another type than number?

I have a function to produce a factorial for a given number, and the initial logic utilizes an if loop to rule out negative numbers or non-number values. However, when I input a string for the argument, it returns the value ‘undefined’ but does not produce the warning message I provided.

Here is code:

function factorial(number) {
  for (let i = number; i >= 0; i--) {
    if (typeof i !== "number") {
      console.log("Write a number....or else, yark-o!");
    } else if (number == 0) {
      return 1;
    } else if (number < 0) {
      return NaN;
    } else if (typeof number == Number) {
      return NaN;
    } else {
      return number * factorial(number - 1);
    }
  }
}

console.log(factorial(0));
console.log(factorial(4));
console.log(factorial(10));
console.log(factorial("potato"));
console.log(factorial(-2));

The current iteration has my typeof i !== 'number' condition resulting in a console log, but I have also tried using the string "Write a number….or else, yark-o!" as a return value instead of console log. Both options yield only the "undefined" return value.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The reason why you’re getting an "undefined" return value when passing a string to your factorial() function is because the loop is never entered since the input is not a number, and thus the function returns nothing. The console.log() statement in your if loop is never executed since the loop is never entered.

To fix this issue, you can move your type check outside of the loop and return an error message if the input is not a number. Here’s an updated version of your code:

function factorial(number) {
  if (typeof number !== "number") {
    return "Write a number....or else, yark-o!";
  } else if (number == 0) {
    return 1;
  } else if (number < 0) {
    return NaN;
  } else {
    return number * factorial(number - 1);
  }
}

console.log(factorial(0));
console.log(factorial(4));
console.log(factorial(10));
console.log(factorial("potato"));
console.log(factorial(-2));

With this updated version, when a non-number value is passed to the function, it will return the error message "Write a number….or else, yark-o!" as expected.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading