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

nasser mohammed
nasser mohammed
13,160 Points

Testing for Number Arguments Pass a string argument

Hi. When I pass a string argument like '10', the function not work well, either when I did the testing.

const getRandom = (lower, upper) => {
  if (isNaN(lower) || isNaN(upper)) { 
  document.querySelector('main').innerHTML = `<h2>The 2 values should be numbers</h2>`;
  } else {
    const random = Math.floor(Math.random() * (upper - lower + 1)) + lower;
  const main = document.querySelector('main').innerHTML = `<h2>${random} is a random number between ${lower} and ${upper}<h2>`;
  return main;
  }
};


getRandom('10',40);

the result is: 310 is a random number between 10 and 40

1 Answer

Travis Alstrand
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Travis Alstrand
Treehouse Teacher

You can see in the docs here it says ... "The isNaN() function determines whether a value is NaN when converted to a number. Because coercion inside the isNaN() function can be surprising, you may alternatively want to use Number.isNaN()."

So it's taking your string of '10' and returning true after converting it to a number.

isNaN()