let chooseANumber = Number(prompt('Choose a number')); if (chooseANumber === 0) { console.log(0); }
('Above the problem i am facing is if user closes the prompt window still 0 is logged into the console and if the user does not input anything still the Number(prompt) will change NaN into 0 and again 0 is logged. What can i do to change the condition to falsy if user does not input anything or closes the prompt window.');
I could not find any solution without changing first line.
CodePudding user response:
Do not convert prompt return value to number immediately. When users closes prompt return value is NULL. But NULL is coerced to 0. Just check for NULL and then compare value as string or convert it to number if needed.
const v = prompt("Choose number");
if(v !== null) {
//You can convert v to number here if needed
if(v === "0") console.log(0);
}
CodePudding user response:
This should be fine
const chooseNumberStr = prompt('Choose a number');
const chooseNumber = parseFloat(chooseNumberStr);
if (chooseNumber === 0)
{ console.log(chooseNumber); }