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

karan Badhwar
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
karan Badhwar
Web Development Techdegree Graduate 18,135 Points

What to use, when not sure what type of value to receive

What to use parseInt(), parseFloat(), or + Unary operator .

When we are not sure what kind of value we can get it can be a whole number or a decimal number too ? so which one to use out of these 3?

As I checked parseFloat works fine even if the value is whole number or a number with decimal?

1 Answer

It depends on what potential values you might receive, and what you are planning to do with them. If you are sure you are only going to get whole or decimal values, then you actually don't need any of them, unless they are being received as strings that look like numbers. If that is the case, any of them are probably fine, though I would personally tend toward the Unary + operator just because it's the shortest to write. If you might get values like true or false, the Unary + operator might return unexpected results, as it will convert boolean values to 1/0. If you might end up with octal or hex values, then you might opt to use parseInt(), as you can specify the radix for the conversion.