A quick dip into recursion

Brian Kustra
1 min readDec 12, 2015

In this example, you will type this code into something like http://jsbin.com/?js,console. In this case you must answer yes or no to break out of the loop.

var askRecursively = function(question) {
var reply = prompt(question);

if ( reply === ‘yes’ ) {
return true;
} else if ( reply === 'no' ) {
return false;
} else {
alert(‘Incorrent answer! Try Again!’);
askRecursively(question);
}
};

askRecursively(“Am I awesome?”);

Now that you have typed this out in the JavaScript interpreter of your choice I am going to break it down. First, we declare the function called askRecursively, and it takes a string that will be the question that the alert pop-up will ask. Next, declare the variable reply and set it equal to the response from the prompt pop-up that is asking the question from the last step. Now, there are two base cases, and for this example the answers ‘yes’ (the correct choice!) and ‘no’ to the question ‘Am I awesome?’ will break the loop. Else an alert will pop-up that says ‘Incorrent answer! Try again!’ and it will recursively (call itself inside the function) ask the original question. Again, once you invoke this function pop-ups will repeatedly appear on screen until the prompt receives the answer ‘yes’ or ‘no’ all other answer will display the pop-up and re-call the function.

--

--

Brian Kustra

I love psychology, software engineering, and excellent conversation