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 Basics (Retired) Creating Reusable Code with Functions Random Number Challenge, Part II

ian izaguirre
ian izaguirre
3,220 Points

My IF statement does not run how I would expect with my OR operator, it only runs my Else if both are strings?

I set up this challenge a little differently. I am using prompts and not console.log. I do not know what I am doing wrong in my code.

This is what happens:

  • If I answer the first prompt with a string and the second with a number, my result gives no error alert and my final alert is NaN

  • If I answer the first prompt with a string and the second with a string,, my result gives the correct error alert, but my final alert is NaN

  • If I answer both prompts with a number, it runs correctly, it results in my error alert not running and my random number shows correctly.

  • What I want to happen: If the first prompt answer is a string , it should show the error alert, before showing the second prompt. If the second prompt is a string then it should show the error alert again.

function randomCalculation(upper, lower) {
  if ( !isNaN(upper) || !isNaN(lower) ) {

    return Math.floor(Math.random() * (upper - lower + 1)) + lower;

  } else {
    alert('Error! That is not a number');

  }
}


// Two Prompts are run  and each answer is stored in a variable below

var answerOne = parseInt(prompt('Please Input Your Upper Number'));
var answerTwo = parseInt(prompt('Please Input Your Lower Number'));



// The above variables are run as arguments of the function, and
// The result is assigned to the variable below

var runMyProgram = randomCalculation(answerOne,answerTwo);


// We run the above variable
alert( runMyProgram );

Hi, change || to &&

1 Answer

Steven Parker
Steven Parker
231,236 Points

Since you negate the isNaN tests, you should also covert OR into AND.

You only want to perform the calculations if both values are not NaN, so you need an AND operation. An OR operation means "either", so one of them could still be NaN.

And if you want to see an error message before the second prompt, you will need to duplicate the testing logic from the randomCalculation function and place it between the prompt statements.