Complementing the other answers: when the string contains an integer (such as '123'
, '42'
, etc), there is no difference in the result. But when the string is not exactly an integer, the results may be different. For example:
['', ' ', '\n', '7.5', '1x', '1.2.3', '3e2', 'xyz'].forEach(s => {
console.log(`+"${s}" = ${+s} - parseInt("${s}") = ${parseInt(s)}`);
});
Of those, only the string 'xyz'
gives the same result for both cases. The others do not:
+"" = 0 - parseInt("") = NaN
+" " = 0 - parseInt(" ") = NaN
+"
" = 0 - parseInt("
") = NaN
+"7.5" = 7.5 - parseInt("7.5") = 7
+"1x" = NaN - parseInt("1x") = 1
+"1.2.3" = NaN - parseInt("1.2.3") = 1
+"3e2" = 300 - parseInt("3e2") = 3
+"xyz" = NaN - parseInt("xyz") = NaN
For empty string, string containing multiple spaces and string containing line break (\n
), the conversion with +
returns zero, and parseInt
returns NaN
.
For a string that represents a float, +
gives the same result as parseFloat
and keeps the houses after the comma, returning 7.5
. Already parseInt
remove the decimal places and return 7
.
To '1x'
, the +
returns NaN
, while parseInt
returns 1
. This is because according to the specification the unary operator +
, when applied to strings, uses the algorithm described here (that basically does not recognize the character x
and so fails and returns NaN
). Already parseInt
uses a different algorithm: it reads the digits and when it finds something that is not a valid digit, ignores the rest of the string and converts the digits it has read so far, and so the return is 1
(similar what PHP does). The same goes for '1.2.3'
, returning NaN
with the operator +
, but returns 1
with parseInt
.
Already a number in scientific notation ('3e2'
) is correctly recognized by +
, returning 300
. But parseInt
does not recognize this format and returns 3
(for the reason already described in the previous paragraph). In this case, you could use parseFloat('3e2')
, returning 300
.
Finally, for the string 'xyz'
, both return NaN
.
Remember also that there are some bizarre situations that can occur if you pass numbers instead of strings to parseInt
:
console.log(parseInt(0.0000005)); // 5
console.log(parseInt(1000000000000000000000)); // 1
// com o "+" isso não ocorre
// obs: os valores ficam corretos, mas a saída estará em notação científica
console.log(+0.0000005); // 5e-7
console.log(+1000000000000000000000); // 1e+21
Did you find it strange? The explanation is here.
In this reply from Soen has a very complete comparative table, with more cases and the respective results for each conversion. In this same link there are other responses that cite other differences and corner cases.
Testing done on Firefox 68.0.2 and Chrome 76.0.3809.132 (both for Windows 64-bit).
The only advice I can give that is not in the answers is to use the 2nd parameter of
parseInt
to specify the basis of the conversion if by some chance or bad luck you have to support IE8-– fernandosavio