JavaScript JavaScript Numbers Working with Numbers Convert Strings to Numbers

JavaScript Numbers ( + or parseInt)?

I find i'm getting same result in the console.log using either + or parseInt. for example const totalBadges = + HTMLBadges + + CSSBadges; console.log(totalBadges); or const totalBadges = parseInt(HTMLBadges) + parseInt(CSSBadges); console.log(totalBadges);

So does it matter which is used?

Alexander Burdiss
Alexander Burdiss
6,158 Points

They do have different behaviors in some edge cases, although they appear to have the same behavior. Check out this Stack Overflow for a complete explanation of the differences, including a chart documenting every edge case: https://stackoverflow.com/questions/17106681/parseint-vs-unary-plus-when-to-use-which/17106702#17106702

2 Answers

Steven Parker
Steven Parker
201,355 Points

The most significant functional differences are in the handling of empty strings and strings with mixed digits and alpha characters (including scientific notation). The table referenced by Alexander is great for comparing all the various cases with other conversion methods.

But besides functionality, another consideration might be code readability. It can get a bit obscure with the unary plus, particularly when used in math expressions.

Thank you both for your help, I think i would prefer parseInt over + if the code allows just like you say Steven, for readability. As with + can think its a addition when reading code.

Thanks Alexander i will have a look into your link.