Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript JavaScript Basics (Retired) Working With Numbers Numbers and Strings

Why does my code work ??

I didnt use parseint, how did this work

var secondsInAMinute = 60; var minutesInAnHour = 60; var hoursInADay = 24; var daysInAWeek = 7; var weeksInAYear = 52;

var years = prompt("how old are you? : ");

var secondsInYourLife = years * weeksInAYear * daysInAWeek * hoursInADay * minutesInAnHour * secondsInAMinute;

document.write("You have been alive for " + secondsInYourLife + " seconds");

2 Answers

Hi there,

JavaScript is very relaxed about the difference between strings and numbers. When you use string concatenation (where you write out "You have been alive for " + secondsInYourLife + " seconds"), JavaScript interprets the int variables as strings because it sees you're trying to concatenate rather than perform addition. Consider the following code:

 var a = 10;
 var b = 20;
 console.log('result is ' + a + b);

The resulting output would be "result is 1020";

Your code works because you multiplied the value stored in years. Strings concatenate, but only numbers can multiply. If you had answered the prompt with a string that could not return a value on multiplication (like 'twenty' instead of '20'), then your code would not have worked.

Thus another way to turn string into numbers would be multiplying or dividing by 1. This is NOT best practice.