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 trialMariano Okpalefe
4,182 Pointswhat's wrong with my code? it says that on line 4 error is undefined. Is it the order in which i showed my code or what?
function getRandomNumber( lower, upper ) {
var randomNumberGen = Math.floor(Math.random() * ( upper - lower + 1)) + lower;
if ( lower || upper ) {
throw new error("You have to type in a number, not a string you idiot!");
} else {
return randomNumberGen;
}
}
console.log( getRandomNumber( 1, 100 ) );
console.log( getRandomNumber( 200, 'five hundred' ) );
console.log( getRandomNumber( 1000, 20000 ) );
console.log( getRandomNumber( 50, 100 ) );
3 Answers
Maximiliane Quel
Courses Plus Student 55,489 PointsYou need to adapt the condition in your if statement to test that whatever the person enters is only a number. Error is also a constructor that allows you to create an object so it is written with a capital letter at the beginning:
function getRandomNumber( lower, upper ) {
if(isNaN(lower) || isNaN(upper)){
throw new Error('You can only enter number into this function');
} else {
return Math.floor(Math.random() * (upper - lower + 1)) + lower;
}
}
Erik Nuber
20,629 Pointsfunction getRandomNumber( lower, upper ) {
var randomNumberGen = Math.floor(Math.random() * ( upper - lower + 1)) + lower;
if ( isNaN( lower ) || isNaN(upper) ) {
try {
throw new Error("You have to type in a number, not a string you idiot!")
} catch (e) {
console.log(e);
}
}else {
return randomNumberGen;
}
}
console.log( getRandomNumber( 1, 100 ) );
console.log( getRandomNumber( 200, 'five hundred' ) );
console.log( getRandomNumber( 1000, 20000 ) );
console.log( getRandomNumber( 50, 100 ) );
Need a bit of extra coding. Your conditional statement needs to check if it is a number or not.
When you throw an error, Error is capitalized and, when it is thrown, you need to catch it as well. You can do anything with the catch, you can display it to the console, write it to the page etc.
Mariano Okpalefe
4,182 Pointsthanks you guys i just misunderstood completely what i was supposed to be doing, I understand now
Jesus Mendoza
23,289 PointsJesus Mendoza
23,289 PointsIn your code you're basically saying "If lower or upper exist then throw an error". It should be (!lower || !upper). Also it should be new Error, with capitalized E