0

When will NaN be returned and when will 0 be returned ?

console.log(parseInt('3',2)); // NaN

console.log(parseInt('09',8)); // 0
VLAZ
  • 26,331
  • 9
  • 49
  • 67
Robert
  • 1
  • 2
  • `parseInt` will *parse* the input one character at a time until it finds one that it cannot and return the valid ones. `3` is not a base-2 value. Since this is the first symbol, parsing is terminated. The total valid values is nothing. Result is `NaN`. With `09` it parses `0` which is a valid base-8 value. The equivalent in decimal is `0`. Then `9` is *not* a valid base-8 value. Parsing stops. The total valid parsed results is `0`. The same way that if you have `parseInt("50 dollars")` the result is `50` or `parseInt("3.50")` is `3` - in both cases the valid numbers at the beginning are taken. – VLAZ Jan 29 '21 at 10:00
  • `parseInt('3',2)` is NaN because `3` is not a digit in base 2 (binary). Those digits in binary are `0` and `1` only. ... where as `parseInt('13',2)` returns int `1` because as @VLAZ mentions, it stops parsing on next invalid placevalue, in that case `3` – GetSet Jan 29 '21 at 10:09

0 Answers0