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

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
216,083 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
216,083 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! :)