Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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?

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
231,275 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.