Reputation: 18835
I noticed something quite odd this morning when I was trying to implement an endless prompting system.
The following code returns 2 different outputs under 2 scenarios:
Scenario 1: Enter number on first prompt and ok
Output 1: number that was entered
Scenario 2: Cancel first prompt then enter number and ok
Output 2: undefined
I'm perplexed as to why this is happening. Firstly, how does this return undefined when I am checking for that in the if statement? Second, I was under the impression that in JavaScript undefined means a variable has been declared but has not yet been assigned and in this case I am assigning the var number
.
var number = null;
number = Prompt();
$("p").html("Number was " + number);
function Prompt()
{
var input = prompt("Enter a number", "");
if(input === null || input === "" || input === undefined || isNaN(input))
Prompt();
else
return input;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p></p>
Upvotes: 4
Views: 1314
Reputation: 1356
When the first prompt is cancelled another Prompt() iteration is called, but it's return value is not captured anywhere. The first iteration then returns the original undefined return value.
Musa's answer shows one way to fix this. Another would be:
function Prompt() {
var input = null;
while(input === null) {
input = prompt("Enter a number", "");
}
return input;
}
Upvotes: -1
Reputation: 135377
window.prompt
always returns a string or null
so don't bother checking for undefined
, or isNaN
Also, since window.prompt
returns a string, you will need to use window.parseInt
in order to reliably convert it to a Number.
function Prompt() {
var n = window.parseInt(window.prompt("Enter a number"), 10)
if (Number.isNaN(n))
return Prompt()
else
return n
}
alert("Your number is: " + Prompt())
Upvotes: 3
Reputation: 97717
Only one code path returns a value, make it return from the recursive call. In JavaScript if a function ends without a return statement its return is undefined
function Prompt()
{
var input = prompt("Enter a number", "");
if(input === null || input === "" || input === undefined || isNaN(input))
return Prompt();
else
return input;
}
Upvotes: 5