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 trialDazeran Zamri
5,992 PointsMy solution
// User input instead of hardcode
const yearsAlive = prompt('How old are you?');
// Assign another variable to differentiate between years alive and seconds alive
const secondsAlive = yearsAlive * weeksPerYear * daysPerWeek * hourPerDay * minPerHour * secondsPerMin;
alert(`You've been alive for more than ${secondsAlive} seconds!`);
1 Answer
Steven Parker
231,268 PointsPrompting and getting input is cool, but it creates many opportunities for errors unless a great deal of additional code is provided to guard against them.
Be aware that the prompt
function returns a string and not a number, but in this case the system silently performs type coercion for you when you multiply a string containing digits. However, other operations could have caused an error.
For more robust code, always explicitly convert strings of digits into numbers before performing math on them. For example:
const yearsAlive = parseInt(prompt('How old are you?'));
Another potential error arises if the user types something other than digits. For instance, try typing "thirty" (as a word) to answer the prompt. At a minimum, the user should be cautioned to enter digits only. A more complete approach would involve testing for the error and notifying the user and then re-prompting.
You'll find examples of handling these kinds of things in later courses.