Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Start a free Courses trial
to watch this video
Update the random number program to ask for two numbers, then provide a random number between the two.
What if the value of lowNumber
is 0
?
The number zero is considered a "falsy" value in JavaScript. In other words, if the value of lowerNumber
is 0
, the if
condition evaluates to false
, and the code in the else
clause runs.
To make the number 0
an acceptable lowNumber
value in the random number program, use the 'greater than or equal tooperator (
>=`) in the condition:
if ( lowNumber >= 0 && highNumber ) {
...
} else {
...
}
Another approach using isNaN()
JavaScript provides a special function called isNaN()
(or "is not a number") that takes one argument and returns a boolean value. It returns true
if the value is NOT a number, and false
if it is.
isNaN()
returns the value true
. However, passing it an actual number, like 6
, returns false
.
In this case, you first test if EITHER variable is not a number. If even one is not a number, display the "Try again" message. To test both variables, use the logical OR (||
) operator:
// Convert the input to a number
const lowNumber = parseInt(inputLow);
const highNumber = parseInt(inputHigh);
// Check if lowNumber OR highNumber is not a number
if ( isNaN(lowNumber) || isNaN(highNumber) ) {
console.log('You need to provide two numbers. Try again.');
} else {
// Use Math.random() and the user's number to generate a random number
const randomNumber = Math.floor( Math.random() * (highNumber - lowNumber + 1) ) + lowNumber;
// Create a message displaying the random number
console.log(`${randomNumber} is a random number between ${lowNumber} and ${highNumber}.`);
}
Resources
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up