0

I'm using the Number js object to get a number from a string. For example:

Number("123") -> 123
Number(":") -> NaN

but when I'm trying Number(" ") the result is 0 and with parseFloat(" ") the result is Nan that's unclear to me why space output is a 0 with Number and NaN with parseFloat

Ar26
  • 949
  • 1
  • 12
  • 29
  • 1
    Because javascript is weird!? And it was defined that way. – luk2302 Feb 10 '22 at 13:58
  • 5
    As with most of this type of question: [Because the spec says so](https://tc39.es/ecma262/#sec-runtime-semantics-stringnumericvalue) – Quentin Feb 10 '22 at 13:58
  • 1
    it's like `Number("")` but after using `trim()` – Yasser CHENIK Feb 10 '22 at 13:59
  • 4
    As a guess I’d say that the function does its best to coerce the input into a number. It probably trims the input so space becomes an empty string, which can be coerced to a false value, which can be coerced into zero – Jamie Dixon Feb 10 '22 at 14:00
  • Because the [specification](//tc39.es/ecma262/#sec-number-constructor-number-value) says so. – Sebastian Simon Feb 10 '22 at 14:00

0 Answers0