0

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

MarleneHE
  • 334
  • 4
  • 17
Lola pinky
  • 13
  • 2

1 Answers1

1

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.

Bugs Bunny
  • 2,496
  • 1
  • 26
  • 32