-3

The code ran in developer console is shown below. Why does parseInt return the number present in [0]th index of a string but not return the number present in any other index in the string?

parseInt('i am 1 year old')
// output NaN
parseInt('1 year old')
// output 1

What is the reason why it behaves like this?

Vinod kumar G
  • 639
  • 6
  • 17
  • 1
    Possible duplicate of [Why does Javascript parseInt('0x4A') return the same as parseInt('0x4Avv')?](https://stackoverflow.com/questions/29781856/why-does-javascript-parseint0x4a-return-the-same-as-parseint0x4avv) – Thilo Sep 02 '17 at 04:32
  • 1
    it is attempting to parse the string. It sees the first character is a numeric and everything after is not, so it sees just 1. when it tries to cast i, it sees that *i* is not a numeric. you can see it with various input tests of `parseInt('5trees');` and `parseInt('16 candles');` – Fallenreaper Sep 02 '17 at 04:32
  • 1
    Because that's how it is defined to work, as stated clearly in the [documentation](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/parseInt). –  Sep 02 '17 at 04:36

1 Answers1

2

The parseInt function reads the string to a point it keeps getting numbers. So, 10 is a number returns 10 because the function stops at third character, which is a space. But in case of i am 1 year old, it stops at i because it is not a number and returns NaN instead.

If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point. parseInt truncates numbers to integer values. Leading and trailing spaces are allowed.

Reference: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/parseInt

Nisarg Shah
  • 14,151
  • 6
  • 34
  • 55
  • The relevant excerpt of the docs is this: "An integer number parsed from the given string. If the first character cannot be converted to a number, NaN is returned." The answer is completely right though, don't know why someone would downvote it. – ishegg Sep 02 '17 at 04:34
  • 1
    Well to be fair, I think the information about leading and trailing spaces is important. Also, I wasn't aware of the radix consideration. So I added this paragraph. – Nisarg Shah Sep 02 '17 at 04:38