this is a beginner JS question regarding NaN in an IF statement. I have code below that prompts user to enter a number, and the program will generates a random number between 1 and the user's input. However, IF the user doesn't enter a number, it will prompt user to retry and enter a valid number instead.
const userInput = prompt("Please enter a number.");
const userNumber = parseInt(userInput);
if (userNumber) {
const randomNumber = Math.floor( Math.random() * userNumber ) + 1;
console.log(`${randomNumber} is a number between 1 and ${userNumber}`);
} else {
console.log(`Please enter a valid number.`);
}
The question I have is the userNumber section of the IF statement. The condition is basically asking IF userNumber IS a number, then output the random number. But why is it simply written with the variable in the condition, and not a condition such as if (userNumber != NaN) or if (userNumber == number)? Why is it just the variable in the condition?
To me, reading that line of code I'm thinking: "... if userNumber WHAT? There's nothing after userNumber, so what is the condition?"