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 trialDuy Khanh
Courses Plus Student 4,911 PointsWhat if string like "number" example "22" ?
My solution checking for the string is number like "22 "
function getRandom(num_1,num_2){
var result = 0;
if((isNaN(num_1) === false && isNaN(num_2) === false) || (isNaN(parseInt(num_1)) === false && isNaN(parseInt(num_2))===false )){
if(num_1>num_2){
result = Math.floor( Math.random()*(num_1 - num_2 + 1) )+num_2;
return result;
}else{
result = Math.floor( Math.random()*(num_2 - num_1 + 1) )+num_1;
return result;
}
}
else{
return "Error";
}
}
document.write("<p>Your random number : " +getRandom("22",33)+ " !</p>");
It is right ?
Alissa Kuzina
5,835 PointsI agree with the comment above. In theory... Because for testing values you can use function isNaN which returnes true when your value is not a number. And "22" should be string and in this code
function randomNumber ( min, max) {
if ( isNaN ( max ) || isNaN ( min ) ) { // cheking if min or max are numbers
throw new Error ('Type a number'); // if max/min isn't a number - condition is true and you'll get an error
} else {
return Math.floor(Math.random() * (max - min)) + min; // if min and max are both numbers and condition is false you receive your result
}
}
console.log ( randomNumber ( 10,20 ) ); // everything's alright
console.log ( randomNumber ( "24" , "10" ) ); //
I was expecting an error. But it's not. After this I tested "24" in cosole (with "") and it told me that it isNaN ( '25') = false so I'm a bit confused about this, but "25h" isnt a number.
So the important question would be would anyone type a number like '23' instead of just 23. I don't think so)
1 Answer
Miguel Morell
3,551 Pointsa better way to handle that condition would be to use typeof. That way if the argument is "22" then it would still catch the error. Just write a condition for if( typeof num_1 == "number" && typeof num_2 == "number")
Munish Sharma
Full Stack JavaScript Techdegree Student 5,144 PointsMunish Sharma
Full Stack JavaScript Techdegree Student 5,144 PointsYes it is right because still it is a string we as a human can read it as Number 22 but once you add this "" , it become string so it is no more number.
I saw later that you are parsing string to int ... but program is and not doing any maths to it its concating it so its like 2233.
I think I guess it right :p may be other experienced one can answer it better ...;)