Just posted a codepen if anyone looking at Recursive Javascript functions.  The scenario here could I am sure be tackled other ways but I wanted to do it with a recursive function.

Given an array of random numbers, the function getNewNumber will finish off the array by populating it with the remaining number between 1 and 10, done in a random order.

var bunchOfNumbers = [1,4,5];
var getNewNumber = function(){
    var tempNo = Math.ceil(Math.random()*10);
    tempNo ? 11 : tempNo--;
    for (var i = 0; i < bunchOfNumbers.length; i++) {
        if (bunchOfNumbers[i] == tempNo) {
          document.getElementById('error').innerHTML += "Number in use:"+tempNo+"<br>";
           return getNewNumber();
        }
     }
    bunchOfNumbers.push(tempNo);
    if(bunchOfNumbers.length < 10){
      return getNewNumber();
    }else{
      return true;
    }
}
getNewNumber();
console.dir(bunchOfNumbers);
document.getElementById('msg').innerHTML = bunchOfNumbers.toString();

I needed a version of this for ensuring an object was not placed at the same coordinates as other objects in an array of coordinates.

View Codepen

Post Script

Some more thoughts on this. Here is an example that checks to see if a PIN number is unique. I am using Firebase to store the PINs.

var getNewNumber = function(){
  var newPin;
  newPin = Math.round(Math.random()*100000)+10000;
  newPin = String(newPin);
  newPin = newPin.substring(1, 5);
  db.ref('cpUsers/').orderByChild("pin").equalTo(newPin).on("value", function(snapshot){
	if(snapshot.val() === null){
             db.ref('cpUsers/').push({pin: newPin}).then(function(snapshot){
	     return snapshot.key;
	     },function(error){console.info(error)});
	}else{
	    return getNewNumber;
	}
   });
}

2 Thoughts to “Recursive Javascript Functions”

  1. agent_x

    Hi, can you please explain the significance of this ternary expression?

    tempNo ? 11 : tempNo–;

    1. admin

      This is just like an if/else. If the tempNo is equal to 11 then return it by one so that it stays in the range 1-10

Leave a Comment