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 The Random Challenge Solution

Could we use +prompt() instead of parseInt() ?

Just because it is shorter ? What is the most common practice ?

var firstNumber = +prompt('Enter your first number');
var secondNumber = +prompt('Enter your second number');
var randomNumber = Math.floor(Math.random() * (secondNumber - firstNumber + 1) + firstNumber);

document.write(randomNumber + ' is a number between ' + firstNumber + ' and ' + secondNumber);
Savannah Lynn
Savannah Lynn
13,662 Points

Hi Marina,

Where did you learn about +prompt()? I can't find any documentation on it. Does the + before it work like parseInt() in that it converts it to an integer?

Yes Savannah. That is more simple way to convert string to the number. But you are right it would be just a number, but not always an integer?

To put before the expression unary plus "+" Just try some examples in console as:

var a = +"123"; // 123: 
var a = Number("123"); // 123,

alert( +"   \n  123   \n  \n" ); // 123

alert( +true ); // 1
alert( +false ); // 0

Type              Result
undefined         NaN
null              0
true / false      1 / 0

console.log(+value);  // number

3 Answers

Savannah Lynn
Savannah Lynn
13,662 Points

I'm guessing that is the limitation with using + only. If you really need it to be specifically an integer, parseInt is probably still the safest. Thanks for teaching me that trick though!

Raphaël Seguin
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Raphaël Seguin
Full Stack JavaScript Techdegree Graduate 29,228 Points

Hi, I didn't know that trick either. Thank you. I found that one alter, which could interest you :

~~98.2392847; // 98
~~0; // 0
~~0.12134; // 0
~~1.0000002 // 1

It always returns the entire part !

Thanks for the answer to my question @Savannah