Zze Zze - 4 months ago 21
Javascript Question

Recursive prompt returns undefined

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>




Answer

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;
}
Comments