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) Creating Reusable Code with Functions Random Number Challenge

Russell Smitheram
Russell Smitheram
2,009 Points

I can't figure out the math

This is the first challenge that's got me stuck.

I can't figure out why the function is returning numbers thar are smaller than the numbers I've given it.

https://w.trhou.se/vtk80i1uyh

For example, I passed two numbers (5, 10) to my function but on the console.log it returns 1, 2 and even minus numbers.

I'm sure I'm messing up the math part...

If anyone can help I'd truly appreciate it.

4 Answers

Michael Hulet
Michael Hulet
47,913 Points

It looks like you're currently passing parameters into Math.random itself, which takes no parameters. It will always return a random number between 0 and 1 and will ignore whatever parameters you pass it. As for the math, you actually look to be on the right track. The MDN documentation on Math.random has some good sample code to show a good solution. Basically you multiply the result of Math.random() by the result of (max - min), which will put the random number in a range that might be below your minimum, but close to the range that you want. After that, you add min to it, in order to guarantee that it will never be less than that minimum. However, since you previously multiplied it by (max - min), it will never be greater than (or equal to) max. Thus, it's a random number in the range you want

Tyler Dix
Tyler Dix
14,230 Points

This explains the math! I did a bunch of fiddling around, and didn't quite understand the math behind this.

function sayThanks (helper) {
    return "Thanks " + helper + "!";
}

alert(sayThanks("Michael H."));
Katiuska Alicea de Leon
Katiuska Alicea de Leon
10,341 Points

Why do the examples have to be math all the time? Ugh!

function randNum(low, high) {
  rand = Math.floor(Math.random() * (high - low + 1)) + low; 
  return rand;
}
document.write('<p>You\'re random number is ' + randNum(5, 10) + '</p>');
Piotr Manczak
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Piotr Manczak
Front End Web Development Techdegree Graduate 29,367 Points

In my opinion it should look something like that:

function aNumber (num1, num2) { var randomNumber = Math.floor(Math.random() * (num2 - num1)) + num1; return randomNumber; }

console.log(aNumber (-500, -50));