3

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.

nicael
  • 18,550
  • 13
  • 57
  • 90

2 Answers2

5

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.)

Ry-
  • 218,210
  • 55
  • 464
  • 476
5
parseInt(bool) == NaN
parseInt(bool*1) == parseInt(int) == int

I believe Javascript makes true = 1 and false = 0 when you multiply it.

EDIT: to further this, parseInt(bool*bool) would also work

Sam Creamer
  • 5,187
  • 13
  • 34
  • 49