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

Y G
Y G
1,440 Points

JavaScript random number generator efficient code question.

For the random number generator coding exercise, this is the code I wrote. This code worked but I have a question about its efficiency. Is there a better way to write this code or can this method be problematic later on?

var userNumber = prompt("Please choose a number."); document.write(Math.floor(Math.random() * parseInt(userNumber)) + 1);

Thank you for your help in advance!

Dave McFarland

3 Answers

Steven Parker
Steven Parker
229,732 Points

This approach is about as efficient as you can get for generating and displaying a single number.

As you progress in the courses, you'll see examples of how to separate code into sensible sections, and use functions to make the code easily re-usable and eliminate redundancy in larger programs.

Y G
Y G
1,440 Points

Okay that's good to hear! Thank you. This is the code I wrote for the second part of the challenge.

var num1 = prompt("Please choose a number.");

var num2 = prompt("Please choose a number.");

document.write(Math.floor(Math.random(parseInt(num1)) * parseInt(num2)) + 1);

Steven Parker
Steven Parker
229,732 Points

It's good to understand how optimizations can be applied, but sometimes they can "box in" development if applied too early.

For example, in this case the formula in the video can be easily converted into a separate function, but the one shown here with the conversions embedded within it would need re-writing.

Y G
Y G
1,440 Points

Duly noted. Thank you so much for your input Steven! :)