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 Introducing the Practice

Why does parseFloat() applied in a different order provide a different result?

If you copy all of this code into the console:

var x = prompt("Enter a number:"); console.log(typeof(x)); parseFloat(x); console.log(typeof(x));

the output after both console.logs is "string" AND "string". But when you do it like this:

var y = parseFloat(prompt("Enter a number")); console.log(typeof(y));

then, the result after the console.log is "number"

I do not understand what is causing this. I was expecting the first case to output "string" first and "number" after the second console.log, once the parseFloat function was applied to the variable x.

1 Answer

Stephan Olsen
Stephan Olsen
6,650 Points

The parseFloat method takes a string as argument and then returns a number. So when you call parseFloat(x), it doesn't do anything, because you don't do anything with the return value. If the return value in a variable, and tried to check the type of it, it would in fact be a number.

var x = prompt("Enter a number:"); 
console.log(typeof(x)); // string
x = parseFloat(x); 
console.log(typeof(x)); // number

Thank you Stephan. Got it.