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 Basics (Retired) Working With Numbers Numbers and Strings

Clara Marquina
PLUS
Clara Marquina
Courses Plus Student 5,189 Points

Why this string was treated as an integer by JavaScript without the Parse method?

In the previous exercise (calculate your age in seconds) I add a prompt to ask the user for its age to customize the seconds depending ion the user. I didn't use the parse method, buy JavaScript convert the string prompt in to a Integer and gave the result. How is that possible? is it because the other variable that uses for the calculation is an integer?

Here's my code:

//variables
var secondsPerMinute = 60;
var minsPerHour = 60; 
var hoursPerDay = 24;
var DaysPerYear = 365.25;
//Seconds in a day
var SecondPerDay = secondsPerMinute * minsPerHour * hoursPerDay;
document.write("There are " + SecondPerDay + " seconds in a day.");
//Seconds in a Year
var SecondsPerYear = SecondPerDay * DaysPerYear;
document.write("There are " + SecondsPerYear + " seconds in a year. ");
//Living seconds of the user
var yourAge = prompt("How old are you?");
var livingSeconds = yourAge * SecondsPerYear;
document.write("You've been alive " + livingSeconds + " seconds. Wow!");

1 Answer

Billy Bellchambers
Billy Bellchambers
21,689 Points

Hi Clara,

I believe this is part of the forgiving element of JavaScript if the user only enters a number JS will treat it as a number moving forward in the rest of the calculations where possible.

However its a best practise to include the parseInt() function for prompt entries that will later be manipulated as if the user enters anything other than a simple number your code will fail.

for example.

var yourAge = prompt("How old are you?"); 

//where yourAge = simple number such as 8. --code works fine.
//if yourAge = a string such as "8 years" for example -- code will not work unless the parseInt("8 years") is run to give back parseInt(yourAge) = 8;

Hope that helps

Had the same question, thanks!