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 trialMytech T
Full Stack JavaScript Techdegree Student 1,427 PointsIs this solution acceptable?
check this solution, please.
const random = (upper, lower) => typeof(upper,lower) === 'number' ? Math.floor(Math.random() * (upper - lower + 1)) + lower : `That's not a number`
console.log(random(20, 10))
4 Answers
Steven Parker
231,275 PointsYou can only use "typeof" on one thing at a time.
If I try "console.log(random(20, "Joe"))
" I get "That's not a number
"
But if I try "console.log(random("Joe", 10))
" I just get "NaN
"
Mytech T
Full Stack JavaScript Techdegree Student 1,427 PointsSteven Parker, but it worked, try it on the console?
Steven Parker
231,275 PointsSee the examples added to my answer.
Mytech T
Full Stack JavaScript Techdegree Student 1,427 PointsSteven Parker, Yep, you rightπ
Joseph Lander
Full Stack JavaScript Techdegree Graduate 27,765 PointsI think this is interesting as to the difference between isNaN() and typeof X === 'number'. [I figure they must be different or why would both exist?]
I wrote a similar logic with typeof before watching the solution. To explore the difference I changed my upper number check to isNaN and ran the following code:
const randomNumber = (lower, upper) => {
if (typeof lower !== 'number' || isNaN(upper)) {
throw Error('parameters are not both numbers');
}
return Math.floor(Math.random() * (upper - lower + 1)) + lower;
};
console.log(randomNumber(2, '4')); // 4 as a string is coerced/considered a number
console.log(randomNumber('two', 4)); // 'two' does NOT get coerced/considered a number - throws error
Joseph Lander
Full Stack JavaScript Techdegree Graduate 27,765 PointsPS Like your use of a ternary Mytech T. More concise than mine.