Ucenna Ucenna - 4 months ago 24
Javascript Question

How to 'return' out of a parent function from it's child?

I frequently use a verifyInput function inside my projects to ensure I get a valid input from users. Now and again I find myself wishing that I could exit my parent function from my verifyInput. verifyInput is usually given a

function. Prompts, have cancel keys. I'd like to exit my nested expression if cancel is clicked. How would I do this?

function verifyInput(foo, value){
const input = foo();
if (!isNaN(input) && !input || input === null || input === undefined){
if(input === null){
/*The input is null, because they hit the cancel button. I should exit myLoop here.*/
} else {
alert("Not valid.");
return verifyInput(foo,value);
} else {
if(value && input.search(value) < 0){
alert("'"+[input]+"' is not a valid input.");
return verifyInput(foo,value);
return input;

function myFunc(){
var myInput = verifyInput( () => prompt("What is your input?"));
return myFunc();


There's no way to directly stop the execution of the caller (myLoop) directly from verifyInput unless you throw an exception.

As others said, you could check the return value from myLoop to stop it conditionally.

But maybe a cleaner solution would be using a callback for that, which would only be called if the input is not "exit". This callback would be responsible for getting the input if it's valid and calling myFunc again to continue the loop. Example:

function verifyInput(prompter, callback) {
  var value = prompter()

  if (value === "exit") {
    return // don't proceed with the callback if `value` is "exit"

  if (invalid(value)) { // function to be implemented
    return verifyInput(prompter, callback)


function myFunc() {
  var prompter = () => prompt("What is your input?")
  verifyInput(prompter, (value) => {
    console.log(value) // logs the input


FIDDLE: https://jsfiddle.net/guisehn/r1Lwxkhp/