Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive prompt returns undefined

Tags:

javascript

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>
like image 388
Zze Avatar asked Mar 12 '23 18:03

Zze


1 Answers

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;
}
like image 80
Musa Avatar answered Mar 31 '23 07:03

Musa