Search code examples
functionparseint

Why in my function parseInt doesn't return the 0 from the string I pass to it?


parseInt doesn't return 0 when I use it in the function below :

    const getGuestsCount = guestsInput => {
  if (parseInt(guestsInput)) {

    return parseInt(guestsInput);
  }

  return 'not a number';
};

For example, getGuestsCount('0 we won\'t visit you!!'); returns "not a number"

But if we use parseInt outside of the function then it's ok, parseInt('0 we won\'t visit you!!'); returns 0 as expected


Solution

  • Since parseInt('0 we won\'t visit you!!') evaluates to 0, your IF condition is negative and the function thus returns not a number.

    Maybe you're looking for if (!isNaN(parseInt(str)) { ... }?

    const getGuestsCount = guestsInput => {
      var guests = parseInt(guestsInput, 10);
    
      if (!isNaN(guests)) {
        return guests;
      }
    
      return NaN;
    };
    

    Also, checking for numbers in JavaScript is a bit cumbersome, you should check Confusion between isNaN and Number.isNaN in javascript and other suggested resources to better understand the problem.