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

parseInt clarification

ok, so if I understood correctly when using the prompt method for collecting numbers, the data collected will be converted into string right? so we need to use parseInt to convert them to numbers again.

I wrote a small ROI formula and as you can see I am not using the parseInt method in the formula and it works just fine. Conversely, when I add the parseiNT method the formula stops working

alert("Ok, so we will calculate your ROI now mate !");

var gainInvestment = prompt("What was the gain from your investment?"); var costInvestment = prompt("What was the cost of your investment?");

var roi = (gainInvestment - costInvestment) / costInvestment;

document.write("OK, so your ROI should be " + roi);

Any explanation for this?

Thanks in advanced

1 Answer

JavaScript always tries to convert values to whatever the operation you are performing requires them to be. Since there is no way to subtract strings or divide them JavaScript is smart enough to understand that you want to have the strings treated as numbers (which can be subtracted and divided) and converts them automatically.

The reason why it is recommended to use parseInt when working with numbers is the fact that for ambiguous operations like + JavaScript will not automatically convert them to numbers. + is ambiguous because it is a valid operation on both strings and numbers. When used on strings it simply glues the strings together "Hello" + "World" becomes "HelloWorld" for example, and with numbers it obviously uses addition on them.

So if you had two numbers stored as strings using + on them would result in them simply being glued together, "1" + "1" for example would become "11" because they would be treated as strings.

As for parseInt causing issues, are you sure you used it correctly? I tested your code with and without parseInt and did not notice any differences. And logically there shouldn't be any as JavaScript is converting the strings into ints in either case.

Hey Andren, thanks for your explanation it's clear in my head now!. oN the other hand, I might have an error with parseInt really appreciate you help

Martin