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

Please explain

Can someone please explain. See code below. When removing the parseInt on line two the code still works. However, without the parseInt it dosen't round the number to a whole input by the user. For example user = 3.3 return = 3 (parseInt).

What i would like to know, can someone please give me a simple example to where I would need the parseInt in real life. Does it matter that I have or have not used parseInt in this code and what scenario where it would matter if I did not use the parseInt. Hope I'm making sense.

var input = prompt("Plese type a number");
var topNumber = parseInt(input);
var randomNumber = Math.floor(Math.random() * topNumber) + 1;
var message = "<p>" + randomNumber + " is a number between 1 and " + topNumber + ".</P>";
document.write(message);

2 Answers

Steven Parker
Steven Parker
243,318 Points

The parseInt function converts the input from a string into a number. It doesn't actually "round" but it ignores anything that is not a digit (and what follows).

If you leave it out, then when you multiply by topNumber, the system performs "type coercion" for you, converting the string into a number (but not forcing it to be "int").

But using the parseInt, your program is in control of when, and how, the conversion happens.

great thanks

Hi Desmond,

Say you have 2 numbers that come from user input as strings. If you tried to add these two strings together you would end up concatenating them. If you parse these values as integers they will be mathematically added.

A simple example:

let number1 = "10"; //user input
let number2 = "4"; // user input

console.log(number1+number2); // 104
console.log(parseInt(number1)+parseInt(number2)); // 14
Steven Parker
Steven Parker
243,318 Points

:x: That's not quite correct. In the original example, concatenation is not a possibility because the operation is multiplication. See my answer for the correct explanation.