Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why parseInt() doesn't convert "true" to number, while multiplying does? [duplicate]

Tags:

javascript

I started from expression returning true (I choose 1==1) and wrote it in console

cosole.log(1==1);

It logs true. Now I want to convert it to integer (1) and wrap it in parseInt()

console.log(parseInt(1==1));

It logs NaN. Looks like it is trying to convert 1==1 to string before it converts it to number. Then I'll simply multiply 1==1 by 1.

console.log((1==1)*1);

It logs 1.

Why in first case it converts it converts true to string before converting it to integer (resulting NaN) while I want to convert it to string and in the second case it converts true directly to integer? I'd expect that true*1 will be NaN too.

like image 323
nicael Avatar asked May 10 '26 20:05

nicael


1 Answers

parseInt, by virtue of being a “parse”r, should take a string and produce an integer, so it converts its argument to a string. *, because it’s multiplication, converts its arguments to numbers.

If you want to convert anything to an (32-bit) integer, | 0 works; it’s a 32-bit bitwise integer operation, and can’t result in NaN, because that’s not a 32-bit integer.

Just to emphasize that parseInt is a wholly inappropriate way of casting anything but a string to an integer: what does this give you?

parseInt(5000000000000000000000000)

(For numbers that big, use Math.round(x), or Math.round(+x) if you like to be explicit.)

like image 171
Ry- Avatar answered May 12 '26 09:05

Ry-



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!