Last Updated: October 07, 2020
·
1.147K
· forivall

Don't bother with `parseInt`

For the vast majority of its uses, javascript's parseInt can be replaced with a simple (0|...)

Huh?

Here, I'll show you:

parseInt(input, 10)

Can be rewritten as

(0|input)

There are a few cavaeats, those of which I know are:

> parseInt("notanumber")
NaN
> 0|"notanumber"
0
> "123trailingcharacters"|0
0
> parseInt("123trailingcharacters")
123
> parseInt("1000000000000000") // anything above 2147483647 or below -2147483648
1000000000000000
> 0|1000000000000000
-1530494976

But of course, the bonus is that you don't need to worry about leading zeros, and it's much, much faster, especially when you're just using parseInt as a signed floor for variables that are already numbers.

8 Responses
Add your response

You can also use:

+"3" // 3

+"100" // 100

over 1 year ago ·

Cool, so let's all make our code /less/ readable!

over 1 year ago ·

What @fardjad said. Otherwise, Douglas Crockford will come out from the browser console and tear you apart!

over 1 year ago ·

@lightyrs not every time.
-> parseInt("23.33")
// 23

-> +"23.33"
// 23.33

;)

over 1 year ago ·

@fardjad @gnclmorais Whoops, that's one of the other advantages that I forgot to add. My first usage does have the radix, however. In fact, it was looking at others' code that didn't use the radix that made me think of this problem in the first place.

over 1 year ago ·

@demianbrecht using a unary + prefix to coerce to number, !! to coerce to boolean, and ''+ to coerce to string are commonplace, so as long as it's in your project's style guide, readability shouldn't be a problem here, since it's re-using preexisting commonplace idioms. If, in your styleguide, you use Number(), Boolean(), and String(), then I would advocate continued usage of parseInt().

over 1 year ago ·

@forivall: If unary + prefix to coerce to number is part of your project's style guide, I would feverishly argue that the style guide should be changed. Using language hacks over features implemented specifically to solve the same problems is essentially just a way for a programmer to say "Hey guys, look how awesome I am!".

Code should be just as easy for someone brand new to the codebase to read as for the person who wrote it. Someone not familiar with your project's "style guide" will spend time figuring out what's going on and why it's being done that way. On the flip side, using the obvious functions will incur no reading overhead.

over 1 year ago ·