Jagadesha NH Jagadesha NH - 1 month ago 10
Javascript Question

Why doesn't Number(window.prompt) convert the string to an integer



var numberOne= Number(window.prompt("Type a number", ""));
//in prompt I entered "99" and I get output NaN
console.log(numberOne);

var numberTwo = "99";
console.log(Number(numberTwo));





Why am I getting NaN when I use Number with prompt

Answer

The reason this is happening is because window.prompt already returns a string. So when you enter "99", you are effectively trying to cast '"99"' to a Number, which can't be done.

From https://developer.mozilla.org/en-US/docs/Web/API/Window/prompt

Please note that result is a string. That means you should sometimes cast the value given by the user. For example, if his answer should be a Number, you should cast the value to Number.