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

I prompted the user for a number, did math with it (no parsing), and it worked! Am I missing something?

In the 'seconds you've been alive' challenge, I modified the code to prompt the user for the value of the variable YearsAlive. Then I ran the multiplication with that number to return the seconds the user has been alive. The code worked fine without parseInt or parseFloat.

From my understanding of the Numbers and Strings video, my YearsAlive value should have come back as a string and messed up my calculations. But it didn't! Is parseInt just a best practice for scenarios I haven't seen yet?

Ken Alger
Ken Alger
Treehouse Teacher

Weston;

What line of code did you use to receive your input?

Ken

Hi Ken! I used the line:

var yearsAlive = prompt ("How many years have you been alive?");

and then:

var secondsAlive = secondsPerDay*daysPerYear*yearsAlive

Thanks for your help.

1 Answer

In JavaScript you can do the following:

var x = "5" * 2;

And x will equal 10. A string of numbers can have some mathematical operations performed on it that will convert the string into a number, however the following does not behave quit as you might expect:

var y = "10" + 5;

Since the "+" operation is also used to concatenate strings, y actually equals "105" instead of 15.

Converting to int or float gives you more control of the data types you are dealing with, and ensures you can perform the operations that you really intend to use.

Thanks Erik, that makes sense. I got away with multiplication , but addition would've given me trouble because of its dual purpose with concatenation.