Hacker News new | ask | show | jobs
by plausibilities 2561 days ago
Why would you use parseInt over Math.round if you only expect a single arg?

Seems like you'd only want to use parseInt if you expect to need radix changes at some point, e.g. converting between hex strings, decimal values, and binary strings

    ['1', '7', '11'].map(Math.round)
    // => [1, 7, 11]

    [["00000001", 2], ["00000111", 2], ["0x0B", 16]].map(x => parseInt(...x))
    // => [1, 7, 11]
2 comments

To someone reading the code, parseInt actually describes what your intent is while Math.round just happens to work because it coerces the type.
If you want to get terse

    ['1', '7', '11'].map(x => +x)
If I didn't care about rounding I'd just use a primitive constructor

    ['1', '7', '11'].map(Number)
This coerces to a number, but not to an integer.
I would hate to see it in code that is being shared in a team, but the following works:

['1', '7', '11'].map(x => ~~x)