4

Given:

var obj={0:21,1:22}

and

var arr=[21,22]

Why does parseInt(obj) return NaN, but parseInt(arr) returns 21?

I had a function where I was either going to pass an int, a hash type object or a plain array. I was expecting parseInt to return NaN for both object and array, thus simplifying argument checking. What gives?

4
  • 1
    Why are you using parseInt() at all? The only two things I would use it for are (a) non-base 10 input, and (b) parsing an input string in a known format like a CSS "10px" where I just want the 10 part. I believe Number([21,22]) returns NaN, as does the unary plus operator +[21,23]. Commented Feb 16, 2017 at 1:46
  • @nnnnnn - Why not? if isNaN(parseInt(argument1)).... Quick and easy. What's the harm? I'm not being flip. I'm genuinely curious. Commented Feb 16, 2017 at 3:31
  • If argument1 is the string "123abc", that's not a valid number, but parseInt("123abc") returns 123. If that's the result you actually want, then sure, use parseInt(), but in my experience it's pretty rare for that to make sense (I gave an example already where it does make sense). If you want to test that a function argument is already a number (and not an object or array) you can use the typeof operator. Commented Feb 16, 2017 at 3:57
  • @nnnnnn - I get your point. Commented Feb 16, 2017 at 4:24

1 Answer 1

8

This is because parseInt tries to coerce the first argument to a string before parsing to an integer. String(obj) returns "[object Object]" and can't be parsed, but String([21,23]) returns "21,23", which parseInt parses until it reaches the unparseable char.

See the parseInt spec:

Let inputString be ? ToString(string).

(Coerce the input to a string).

If S contains a code unit that is not a radix-R digit, let Z be the substring of S consisting of all code units before the first such code unit; otherwise, let Z be S.

(Drop any part of the string starting with non-digit character, so "21,23" -> "21").

Sign up to request clarification or add additional context in comments.

7 Comments

This is correct. String representation of an array is result of joining the array elements.
"This is because parseInt tries to coerce the argument to a string"? The documentation infers otherwise: developer.mozilla.org/en/docs/Web/JavaScript/Reference/…
That's it. Amazing the amount of subtle nuances within programming languages
@AlMamun Why do you think the docs say otherwise? Non-string args converted to a string, yes?
To me the document says parseInt tries to coerce values from string to number.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.