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

Anwar H
Anwar H
921 Points

Are we looking to generate random numbers between the upper and lower numbers and including the upper and lower number?

I might be wrong but my understanding is we're looking to generate numbers "between" two values (an upper and lower number). If I designate an upper and lower number, say (100, 95), I was assuming I'd get 96,97,98, and 99. But the code also gives me 95 and 100 as well. How, can we modify the code to generate only the numbers between two values?

Antony .
Antony .
2,824 Points

post code pls

Anwar H
Anwar H
921 Points

May bad. Here is the code:

function getRandomNumber( lower, upper ) {

return Math.floor(Math.random() * (upper - lower + 1)) + lower; }

console.log( getRandomNumber( 'nine', 24 ) );

console.log ( getRandomNumber( 95, 100 ) );

console.log( getRandomNumber( 200, 'five hundred' ) );

console.log( getRandomNumber( 1000, 20000 ) );

console.log( getRandomNumber( 50, 100 ) );

Antony .
Antony .
2,824 Points

If you want some insight on how this line of code works, i suggest looking at this answer by Jason Anello https://teamtreehouse.com/community/mathfloor-mathrandom-max-min-1-min-explanation

function getRandomNumber(lower, upper) {
    return Math.floor(Math.random() * (upper - lower - 1)) + lower + 1;
}
console.log(getRandomNumber(95, 100));
Antony .
Antony .
2,824 Points

Just for better reading, use the Markdown Cheatsheet on learning how to embed your code https://teamtreehouse.com/community/howto-guide-markdown-within-posts

2 Answers

Steven Parker
Steven Parker
229,005 Points

You are correct, in this case "between" means including the highest and lowest values. Typically with computers (as opposed to mathematics) you will see this word used in the inclusive sense. Another example is the SQL language for databases which has a BETWEEN keyword that is inclusive.

But you can modify the formula to give you an exclusive "between":

    return Math.floor(Math.random() * (upper - lower - 1)) + lower + 1;
Antony .
Antony .
2,824 Points

I said the same thing, but always happy to see you helping around steven! :D

Steven Parker
Steven Parker
229,005 Points

I guess I got distracted for a while as I was composing that!

Anwar H
Anwar H
921 Points

Thanks guys. really appreciate your quick responses!