Number(x) vs parseInt(x);

Whats the difference between these two things? i usually use parseInt() since its the one i learned first… but is there difference the two, or there is one that is more efficient or somethng?

1 Like

Number coerces any value to a number (be it a string, boolean, object, etc), and uses type conversion rules for that value.

parseInt on the other hand expects a string input (if it’s not a string, it’s converted to a string first). parseInt also accepts an optional second argument that tells the string’s number system (binary, hexadecimal, etc).


A moderator just replied on my post OMO!!! Thanks sir but the things youve said are pretty clear but some parts are foreign for me, can you please tell me which is better and which is good for specific purposes?

If you’re converting from a different number system to the familiar base-10 system, you’d use parseInt. For example, if you want to convert the hexadecimal (base-16) value 'a7', you’d use parseInt('a7', 16).

(In general, if parse is in the function name, it expects a string)

Number converts any value to a number according to that value’s conversion rules. The more straightforward rules include:

  • false becomes 0, true becomes 1
  • null becomes 0, undefined becomes NaN
  • If a string looks like a number, it becomes that number. The empty string '' becomes 0. Other strings become NaN.

For most string to number conversions, I think both are interchangeable. However there are differences:

  • As mentioned, if a string doesn’t look like a number, using Number will give you NaN.
  • parseInt reads as many characters as it can from the string, until it hits a character it cannot convert.
const s = '123abxyz';
Number(s); // NaN
parseInt(s); // 123 (123 is valid base-10, and stops as soon as it hits `a`)
  • Number('') gives 0; parseInt('') gives NaN
1 Like

Now thats clear as crystal! So according to your reply, I guess nothings really better between the two and there is no reason to compare both Number converting stuffs for they do specific jobs and they differ in a unique way! Thanks sir Moderator! Youre cool!