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 JavaScript Functions Arrow Functions Testing for Number Arguments

Is 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
Steven Parker
231,236 Points

You 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"

Steven Parker, but it worked, try it on the console?

Steven Parker
Steven Parker
231,236 Points

See the examples added to my answer.

Steven Parker, Yep, you rightπŸ‘

I 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

PS Like your use of a ternary Mytech T. More concise than mine.